Starter RESTful service with websocket notifications using Kotlin, Ktor and Exposed with H2, HikariCP and FlyWay
Updated for Kotlin 2.1.10 and Ktor 3.1.1
Companion article: https://ryanharrison.co.uk/2018/04/14/kotlin-ktor-exposed-starter.html
./gradlew run
8080
. See below Routes section for more information.The starter project creates a new in-memory H2 database with one table for Widget
instances.
As ktor is async and based on coroutines, standard blocking JDBC may cause performance issues when used
directly on the main thread pool (as threads must be reused for other requests). Therefore, another dedicated thread
pool is created for all database queries, alongside connection pooling with HikariCP.
GET /widgets
—> get all widgets in the database
GET /widgets/{id}
—> get one widget instance by id (integer)
POST /widgets
—> add a new widget to the database by providing a JSON object (converted to a NewWidget instance). e.g -
{
"name": "new widget",
"quantity": 64
}
returns
{
"id": 3,
"name": "new widget",
"quantity": 64,
"dateUpdated": 1519926898
}
PUT /widgets
—> update an existing widgets name or quantity. Pass in the id in the JSON request to determine which record to update
DELETE /widgets/{id}
—> delete the widget with the specified id
All updates (creates, updates and deletes) to Widget
instances are served as notifications through a WebSocket endpoint:
WS /updates
—> returns Notification
instances containing the change type, id and entity (if applicable) e.g:
{
"type": "CREATE",
"id": 12,
"entity": {
"id": 12,
"name": "widget1",
"quantity": 5,
"dateUpdated": 1533583858169
}
}
The websocket listener will also log out any text messages send by the client. Refer to this blog post for some useful tools to test the websocket behaviour.
The sample Widget service and corresponding endpoints are also tested with 100% coverage. Upon startup of the main JUnit suite (via the test
source folder), the server is started ready for testing and is torn down after all tests are run.