Share
Embed
Transcript
133 slides
-
Part 1. Introduction & overview Part 2. Persistence with Exposed
Part 3. Non-functional requirements Part 4. Extending Ktor Hands-On Kotlin Web Development with Ktor -
Part 1. Introduction & overview Part 2. Persistence with Exposed
Part 3. Non-functional requirements Part 4. Extending Ktor Hands-On Kotlin Web Development with Ktor Demonstration kitchensink -
For each part, we will: Rules of the game: hands-on
1. Provide you with a starter project 2. Give you some time to add functionality 3. Provide a sample solution and walk you through the code -
IntelliJ IDEA with Kotlin (and Ktor) plugins Setup Docker HTTP
client Database client -
https://github.com/antonarhipov/ktor-workshop Setup % git branch * main branch01 branch02 branch03
branch04 branch05 branch06 branch07 branch08 -
https://github.com/antonarhipov/ktor-workshop Setup % git branch * main branch01 branch02 branch03
branch04 branch05 branch06 branch07 branch08 Initial state, generated application First tests - empty First tests - implementation CRUD implementation Adding structure and DI Database access with Exposed - basics Database access with Exposed - adding relations Database access with Exposed - adding entities Integration testing with Testcontainers -
import com.example.plugins.* import io.ktor.server.application.* import io.ktor.server.engine.* import io.ktor.server.netty.* fun main()
{ embeddedServer(Netty, port = 8080, host = "0.0.0.0", module = Application :: module) .start(wait = true) } fun Application.module() { configureRouting() } -
import com.example.plugins.* import io.ktor.server.application.* import io.ktor.server.engine.* import io.ktor.server.netty.* fun main()
{ embeddedServer(Netty, port = 8080, host = "0.0.0.0", module = Application :: module) .start(wait = true) } fun Application.module() { routing { get("/") { call.respondText("Hello World!") } } } -
import com.example.plugins.* import io.ktor.server.application.* import io.ktor.server.engine.* import io.ktor.server.netty.* fun main()
{ embeddedServer(Netty, port = 8080, host = "0.0.0.0", module = Application :: module) .start(wait = true) } fun Application.module() { routing { get("/") { call.respondText("Hello World!") } } } Start an embedded server with Netty engine on port 8080 -
import com.example.plugins.* import io.ktor.server.application.* import io.ktor.server.engine.* import io.ktor.server.netty.* fun main()
{ embeddedServer(Netty, port = 8080, host = "0.0.0.0", module = Application :: module) .start(wait = true) } fun Application.module() { routing { get("/") { call.respondText("Hello World!") } } } Adding routes -
import com.example.plugins.* import io.ktor.server.application.* import io.ktor.server.engine.* import io.ktor.server.netty.* fun main()
{ embeddedServer(Netty, port = 8080, host = "0.0.0.0", module = Application :: module) .start(wait = true) } fun Application.module() { routing { get("/") { call.respondText("Hello World!") } } } Request mapping -
import com.example.plugins.* import io.ktor.server.application.* import io.ktor.server.engine.* import io.ktor.server.netty.* fun main()
{ embeddedServer(Netty, port = 8080, host = "0.0.0.0", module = Application :: module) .start(wait = true) } fun Application.module() { routing { get("/") { call.respondText("Hello World!") } } } Write response -
Database Persistence Service Routing Model DAO Model DTO HTTP JSON
Libraries, DI, plugins, patterns, best practices, etc Grey area: -
Database Persistence Service Routing Model DAO Model DTO HTTP JSON
Coroutines Libraries, DI, plugins, patterns, best practices, etc Grey area: -
Ktor's approach - explicitness Fine-grained approach to dependencies "Dependency per
plugin" Compatible with JPMS -
TODO: more intro? No "magic". No plugin starts automatically Use
the install() function to con fi gure plugins -
Hands-on time! Use the project generator to create new project.
Add Routing, Content Negotiation, and kotlinx.serialization plugins. Run it!!! What do you see? Warmup -
Hands-on time! Use the project generator to create new project.
Add Routing, Content Negotiation, and kotlinx.serialization plugins. Run it!!! What do you see? Warmup Hint: if you select kotlinx.serialization at the plugins stage of the wizard, the other two will be selected automatically -
Hands-on time! Use the project generator to create new project.
Add Routing, Content Negotiation, and kotlinx.serialization plugins. * Run it!!! What do you see? * - Add more plugins if you like, of course! -
Hands-on time! Use the project generator to create new project.
Add Routing, Content Negotiation, and kotlinx.serialization plugins. Run it!!! What do you see? get("/") { call.respondText("Hello World!") } get("/json/kotlinx-serialization") { call.respond(mapOf("hello" to "world")) } -
Hands-on time! Use the project generator to create new project.
Add Routing, Content Negotiation, and kotlinx.serialization plugins. Run it!!! What do you see? https: // github.com/antonarhipov/ktor-workshop % git branch * main branch01 branch02 branch03 -
Hands-on time! Use the project generator to create new project.
Add Routing, Content Negotiation, and kotlinx.serialization plugins. Run it!!! What do you see? https: // github.com/antonarhipov/ktor-workshop % git branch * main branch01 branch02 branch03 This is our starting point -
Hands-on time! Implement endpoints for CRUD operations for the User
data class. @Serializable data class User( val userId: Int, val userType: UserType, val displayName: String, val link: String, val aboutMe: String? = null ) enum class UserType { REGISTERED, MODERATOR, } -
Hands-on time! Implement endpoints for CRUD operations for the User
data class. @Serializable data class User( val userId: Int, val userType: UserType, val displayName: String, val link: String, val aboutMe: String? = null ) enum class UserType { REGISTERED, MODERATOR, } Tests -
import kotlin.test.* class ApplicationTest { @Test fun testRoot() = testApplication
{ application { routing { get("/") { call.respondText("Hello World!") } } } client.get("/").apply { assertEquals(HttpStatusCode.OK, status) assertEquals("Hello World!", bodyAsText()) } } } Creates a TestApplication -
import kotlin.test.* class ApplicationTest { @Test fun testRoot() = testApplication
{ application { routing { get("/") { call.respondText("Hello World!") } } } client.get("/").apply { assertEquals(HttpStatusCode.OK, status) assertEquals("Hello World!", bodyAsText()) } } } De fi ne functionality to be tested -
import kotlin.test.* class ApplicationTest { @Test fun testRoot() = testApplication
{ application { routing { get("/") { call.respondText("Hello World!") } } } client.get("/").apply { assertEquals(HttpStatusCode.OK, status) assertEquals("Hello World!", bodyAsText()) } } } Use client instance interaction with the TestApplication -
import kotlin.test.* class ApplicationTest { @Test fun testRoot() = testApplication
{ application { routing { get("/") { call.respondText("Hello World!") } } } client.get("/").apply { assertEquals(HttpStatusCode.OK, status) assertEquals("Hello World!", bodyAsText()) } } } -
import kotlin.test.* class ApplicationTest { @Test fun testRoot() = testApplication
{ application { routing { get("/") { call.respondText("Hello World!") } } } client.get("/").apply { assertEquals(HttpStatusCode.OK, status) assertEquals("Hello World!", bodyAsText()) } } } It creates an application instance for each test. What if we want to reuse the application instance for several tests? -
class ApplicationTest { val testApp = TestApplication { application {
... } } val client = testApp.createClient {} @Test fun testRoot() = runBlocking<Unit> { val response = client.get("/") assertEquals(HttpStatusCode.OK, response.status) assertEquals("Hello World!", response.bodyAsText()) } } -
class ApplicationTest { val testApp = TestApplication { application {
... } } val client = testApp.createClient {} @Test fun testRoot() = runBlocking<Unit> { val response = client.get("/") assertEquals(HttpStatusCode.OK, response.status) assertEquals("Hello World!", response.bodyAsText()) } } Alternatively, create TestApplication instance -
class ApplicationTest { val testApp = TestApplication { application {
... } } val client = testApp.createClient {} @Test fun testRoot() = runBlocking<Unit> { val response = client.get("/") assertEquals(HttpStatusCode.OK, response.status) assertEquals("Hello World!", response.bodyAsText()) } } Con fi gure HttpClient for the TestApplication -
class ApplicationTest { val testApp = TestApplication { application {
... } } val client = testApp.createClient {} @Test fun testRoot() = runBlocking<Unit> { val response = client.get("/") assertEquals(HttpStatusCode.OK, response.status) assertEquals("Hello World!", response.bodyAsText()) } } Need to use runBlocking to run in a coroutine scope -
class ApplicationTest { val testApp = TestApplication { application {
... } } val client = testApp.createClient { install(io.ktor.client.plugins.contentnegotiation.ContentNegotiation) { json() } } @Test fun testRoot() = runBlocking<Unit> { . .. ContentNegotiation needs to be con fi gured for the HttpClient -
class ApplicationTest { val testApp = TestApplication { application {
... } } val client = testApp.createClient { install(io.ktor.client.plugins.contentnegotiation.ContentNegotiation) { json() } } @Test fun testRoot() = runBlocking<Unit> { . .. ContentNegotiation needs to be con fi gured for the HttpClient -
HttpClient val response: HttpResponse = client.get("/data") assertEquals(HttpStatusCode.OK, response.status) assertEquals( ...
, response.bodyAsText()) private val testApp = TestApplication { .. . } private val client = testApp.createClient { ... } Make request, check response https://ktor.io/docs/client-requests.html -
HttpClient private val testApp = TestApplication { .. . }
private val client = testApp.createClient { ... } val data = Json.decodeFromString<List<User >> (bodyAsText()) assertEquals( ... , data.size) Deserialize response body into objects val response: HttpResponse = client.get("/data") assertEquals(HttpStatusCode.OK, response.status) assertEquals( ... , response.bodyAsText()) Make request, check response https://ktor.io/docs/client-requests.html -
HttpClient private val testApp = TestApplication { .. . }
private val client = testApp.createClient { ... } val data = Json.decodeFromString<List<User >> (bodyAsText()) assertEquals( ... , data.size) Deserialize response body into objects val response: HttpResponse = client.get("/data") assertEquals(HttpStatusCode.OK, response.status) assertEquals( ... , response.bodyAsText()) Make request, check response val response = client.post("/data") { contentType(ContentType.Application.Json) setBody( ... ) } POST with HttpRequestBuilder https://ktor.io/docs/client-requests.html -
Hands-on time! Implement endpoints for CRUD operations @Serializable data class
User( val userId: Int, val userType: UserType, val displayName: String, val link: String, val aboutMe: String? = null ) enum class UserType { REGISTERED, MODERATOR, } -
Hands-on time! Implement endpoints for CRUD operations @Test fun `get
all data`(): Unit = runBlocking { ... } @Test fun `post data instance`(): Unit = runBlocking { ... } @Test fun `put data instance`(): Unit = runBlocking { ... } @Test fun `delete data instance`(): Unit = runBlocking { ... } @Serializable data class User( val userId: Int, val userType: UserType, val displayName: String, val link: String, val aboutMe: String? = null ) enum class UserType { REGISTERED, MODERATOR, } Implement these tests git branch * branch01 -
Sending responses get("/") { call.respondText("Hello World!") } post("/") { val
user = call.receive<User>() ... call.respond(status = HttpStatusCode.Created, message = "Data added successfully") } Respond with HTTP code Add response content -
Receiving requests get("/") { call.respondText("Hello World!") } post("/") { val
user = call.receive<User>() ... call.respond(status = HttpStatusCode.Created, message = "Data added successfully") } Deserialize request content -
Receiving requests get("/") { call.respondText("Hello World!") } post("/") { val
user = call.receive<User>() ... call.respond(status = HttpStatusCode.Created, message = "Data added successfully") } get("/{userId}") { val userId = call.parameters["userId"] ... } Access request parameters -
Hands-on time! Implement endpoints for CRUD operations for the User
data class. @Serializable data class User( val userId: Int, val userType: UserType, val displayName: String, val link: String, val aboutMe: String? = null ) enum class UserType { REGISTERED, MODERATOR, } routing { route("/users") { get { ... } post { .. . } get("/{userId}") { . .. } put("/{userId}") { . .. } delete("/{userId}") { ... } } } Hint -
implementation("io.insert-koin:koin-ktor:$koin_version") implementation("io.insert-koin:koin-logger-slf4j:$koin_version") Adding Koin build.gradle.kts In Ktor app: install(Koin) {
slf4jLogger() modules(usersDataModule) } val usersDataModule = module { single<IRepository> { RepositoryImpl() } } -
implementation("io.insert-koin:koin-ktor:$koin_version") implementation("io.insert-koin:koin-logger-slf4j:$koin_version") Adding Koin build.gradle.kts In Ktor app: install(Koin) {
slf4jLogger() modules(usersDataModule) } val usersDataModule = module { single<IRepository> { RepositoryImpl() } } fun Application.configureRouting() { val repository by inject<IRepository>() -
Hands-on time! Add Koin (or KodeinDI) dependencies to the project:
implementation("io.insert-koin:koin-ktor:$koin_version") implementation("io.insert-koin:koin-logger-slf4j:$koin_version") -
Hands-on time! Abstract the repository implementation with an interface (UserRepository)
Inject the repository implementation (UserRepositoryImpl) using Koin Don't forget to adjust the tests code! Add Koin (or KodeinDI) dependencies to the project: implementation("io.insert-koin:koin-ktor:$koin_version") implementation("io.insert-koin:koin-logger-slf4j:$koin_version") -
Hands-on time! Abstract the repository implementation with an interface (UserRepository)
Inject the repository implementation (UserRepositoryImpl) using Koin Don't forget to adjust the tests code! class UsersRepositoryImpl : UsersRepository { override fun findAll(): List<User> { TODO("Not yet implemented") } ... git branch * branch04 Add Koin (or KodeinDI) dependencies to the project: implementation("io.insert-koin:koin-ktor:$koin_version") implementation("io.insert-koin:koin-logger-slf4j:$koin_version") -
Adding Exposed: dependencies build.gradle.kts val exposed_version = "0.50.1" implementation("org.jetbrains.exposed:exposed-core:$exposed_version") implementation("org.jetbrains.exposed:exposed-jdbc:$exposed_version")
implementation("org.jetbrains.exposed:exposed-dao:$exposed_version") implementation("org.jetbrains.exposed:exposed-kotlin-datetime:$exposed_version") -
Using Exposed: connecting to DB val database = Database.connect( url
= "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", user = "root", driver = "org.h2.Driver", password = "" ) -
val database = Database.connect( HikariDataSource(HikariConfig().apply { jdbcUrl = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1" username
= "root" driverClassName = "org.h2.Driver" password = "" }) ) Using Exposed: connecting to DB -
val database = Database.connect( HikariDataSource(HikariConfig().apply { jdbcUrl = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1" username
= "root" driverClassName = "org.h2.Driver" password = "" }) ) Using Exposed: connecting to DB transaction(database) { SchemaUtils.createMissingTablesAndColumns(Datum) } -
val database = Database.connect( HikariDataSource(HikariConfig().apply { if (embedded) { username
= "root" password = "" driverClassName = "org.h2.Driver" jdbcUrl = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1" } else { username = "test" password = "test" driverClassName = "org.postgresql.Driver" jdbcUrl = "jdbc:postgresql: // localhost:5432/test" } } )) Using Exposed: connecting to DB Check branch05, Database.kt -
@Serializable data class Data(val id: Int, val text: String) object
Datum : Table("data") { val id = integer("id").autoIncrement() val text = varchar("text", 255) } -
@Serializable data class Data(val id: Int, val text: String) object
Datum : Table("data") { val id = integer("id").autoIncrement() val text = varchar("text", 255) } Datum.selectAll().map { Data(it[Datum.id], it[Datum.text]) } Select and map -
@Serializable data class Data(val id: Int, val text: String) object
Datum : Table("data") { val id = integer("id").autoIncrement() val text = varchar("text", 255) } Datum.selectAll().map { Data(it[Datum.id], it[Datum.text]) } Datum.selectAll().where { Datum.id eq id }.singleOrNull() ? . let { Data(it[Datum.id], it[Datum.text]) } Select and map -
@Serializable data class Data(val id: Int, val text: String) object
Datum : Table("data") { val id = integer("id").autoIncrement() val text = varchar("text", 255) } Datum.selectAll().map { Data(it[Datum.id], it[Datum.text]) } Datum.selectAll().where { Datum.id eq id }.singleOrNull() ? . let { Data(it[Datum.id], it[Datum.text]) } Datum.insert { it[Datum.id] = data.id it[Datum.text] = data.text } Datum.update({ Datum.id eq data.id }) { it[Datum.text] = data.text } update / insert -
Hands-on time! 1. Add Exposed dependencies to the project val
exposed_version = "0.50.1" implementation("org.jetbrains.exposed:exposed-core:$exposed_version") implementation("org.jetbrains.exposed:exposed-jdbc:$exposed_version") implementation("org.jetbrains.exposed:exposed-dao:$exposed_version") implementation("org.jetbrains.exposed:exposed-kotlin-datetime:$exposed_version") https://github.com/JetBrains/exposed -
Hands-on time! 2. De fi ne table objects for the
data classes 1. Add Exposed dependencies to the project val exposed_version = "0.50.1" implementation("org.jetbrains.exposed:exposed-core:$exposed_version") implementation("org.jetbrains.exposed:exposed-jdbc:$exposed_version") implementation("org.jetbrains.exposed:exposed-dao:$exposed_version") implementation("org.jetbrains.exposed:exposed-kotlin-datetime:$exposed_version") https://github.com/JetBrains/exposed -
Hands-on time! 2. De fi ne table objects for the
data classes 3. Implement UserRepository using Exposed with the real database 1. Add Exposed dependencies to the project val exposed_version = "0.50.1" implementation("org.jetbrains.exposed:exposed-core:$exposed_version") implementation("org.jetbrains.exposed:exposed-jdbc:$exposed_version") implementation("org.jetbrains.exposed:exposed-dao:$exposed_version") implementation("org.jetbrains.exposed:exposed-kotlin-datetime:$exposed_version") https://github.com/JetBrains/exposed -
Hands-on time! 2. De fi ne table objects for the
data classes 3. Implement UserRepository using Exposed with the real database 1. Add Exposed dependencies to the project 4. Integrate the new implementation into Ktor application using DI val exposed_version = "0.50.1" implementation("org.jetbrains.exposed:exposed-core:$exposed_version") implementation("org.jetbrains.exposed:exposed-jdbc:$exposed_version") implementation("org.jetbrains.exposed:exposed-dao:$exposed_version") implementation("org.jetbrains.exposed:exposed-kotlin-datetime:$exposed_version") https://github.com/JetBrains/exposed -
object Datum : Table("data_table") { val id = integer("id").autoIncrement() val
text = varchar("text", 255) override val primaryKey = PrimaryKey(id) } object Items : Table("items_table") { val id = integer("id").autoIncrement() val name = varchar("name", 255) val datum_ref = reference("datum_ref", Datum.id) override val primaryKey = PrimaryKey(id) } -
object Datum : Table("data_table") { val id = integer("id").autoIncrement() val
text = varchar("text", 255) override val primaryKey = PrimaryKey(id) } object Items : Table("items_table") { val id = integer("id").autoIncrement() val name = varchar("name", 255) val datum_ref = reference("datum_ref", Datum.id) override val primaryKey = PrimaryKey(id) } -
val dataId = Datum.insert { it[Datum.text] = data.text } get
Datum.id Items.insert { it[Items.name] = item.name it[Items.datum_ref] = dataId } -
val dataId = Datum.insert { it[Datum.text] = data.text } get
Datum.id Items.insert { it[Items.name] = item.name it[Items.datum_ref] = dataId } val item = Item("Some item") val data = Data("Some data") -
Hands-on time! Update the UserRepository implementation to handle the relation
object ContentTable : Table("content") { ... val author = reference("author_id", UserTable.id) Update data classes and application code -
object Datum : Table("data_table") { val id = integer("id").autoIncrement() val
text = varchar("text", 255) override val primaryKey = PrimaryKey(id) } object Items : Table("items_table") { val id = integer("id").autoIncrement() val name = varchar("name", 255) val datum_ref = reference("datum_ref", Datum.id) override val primaryKey = PrimaryKey(id) } -
object Datum : LongIdTable("data_table") { val id = integer("id").autoIncrement() val
text = varchar("text", 255) override val primaryKey = PrimaryKey(id) } object Items : Table("items_table") { val id = integer("id").autoIncrement() val name = varchar("name", 255) val datum_ref = reference("datum_ref", Datum.id) override val primaryKey = PrimaryKey(id) } -
object Datum : LongIdTable("data_table") { val id = integer("id").autoIncrement() val
text = varchar("text", 255) override val primaryKey = PrimaryKey(id) } object Items : IdTable<Int>("items_table") { override val id = integer("id").autoIncrement().entityId() val name = varchar("name", 255) val datum_ref = reference("datum_ref", Datum.id) override val primaryKey = PrimaryKey(id) } -
class DataEntity(id: EntityID<Long>) : LongEntity(id) { var text by DatumEntityTable.text
companion object : LongEntityClass<DataEntity>(DatumEntityTable) } Defining entities -
class DataEntity(id: EntityID<Long>) : LongEntity(id) { var text by DatumEntityTable.text
companion object : LongEntityClass<DataEntity>(DatumEntityTable) } class ItemsEntity(id: EntityID<Int>) : IntEntity(id) { var name by ItemsEntityTable.name companion object : IntEntityClass<ItemsEntity>(ItemsEntityTable) } Defining entities -
class DataEntity(id: EntityID<Long>) : LongEntity(id) { var text by DatumEntityTable.text
companion object : LongEntityClass<DataEntity>(DatumEntityTable) } class ItemsEntity(id: EntityID<Int>) : IntEntity(id) { var name by ItemsEntityTable.name var data_ref by DataEntity referencedOn ItemsEntityTable.datum_ref companion object : IntEntityClass<ItemsEntity>(ItemsEntityTable) } Defining entities -
val date = DataEntity.new { text = "Some text" }
ItemsEntity.new { name = "Some item" data_ref = date } Operations with entities -
val date = DataEntity.new { text = "Some text" }
ItemsEntity.new { name = "Some item" data_ref = date } Operations with entities DataEntity.find { DatumEntityTable.text like "A%" }.toList() -
class DataEntity(id: EntityID<Long>) : LongEntity(id) { var text by DatumEntityTable.text
companion object : LongEntityClass<DataEntity>(DatumEntityTable) } class ItemsEntity(id: EntityID<Int>) : IntEntity(id) { var name by ItemsEntityTable.name var data_ref by DataEntity referencedOn ItemsEntityTable.datum_ref companion object : IntEntityClass<ItemsEntity>(ItemsEntityTable) } Defining entities -
class DataEntity(id: EntityID<Long>) : LongEntity(id) { var text by DatumEntityTable.text
val items by ItemsEntity referrersOn ItemsEntityTable.datum_ref companion object : LongEntityClass<DataEntity>(DatumEntityTable) } class ItemsEntity(id: EntityID<Int>) : IntEntity(id) { var name by ItemsEntityTable.name var data_ref by DataEntity referencedOn ItemsEntityTable.datum_ref companion object : IntEntityClass<ItemsEntity>(ItemsEntityTable) } Defining entities -
DataEntity.find { DatumEntityTable.text like "A%" } .singleOrNull() ?. let {
data -> DataInfo( text = data.text, items = data.items.map { ItemInfo(it.name) } ) } Operations with entities -
DataEntity.find { DatumEntityTable.text like "A%" } .singleOrNull() ?. let {
data -> DataInfo( text = data.text, items = data.items.map { ItemInfo(it.name) } ) } Operations with entities val selectedData = Datum.selectAll() .where { Datum.text like "A%" } .singleOrNull() ?. let { Data( text = it[Datum.text], items = Items.selectAll().where { Items.datum_ref eq it[Datum.id] }.map { Item(it[Items.name]) } ) } DAO vs DSL -
More features & plugins status pages request validation static content
type safe routing default headers, CORS CallLogging, CallId, MDC Logging & monitoring Docker image GraalVM native image