Skip to content

Commit

Permalink
chore: apply 2 indentation
Browse files Browse the repository at this point in the history
  • Loading branch information
osoykan committed Apr 22, 2024
1 parent d4e4f90 commit d4a7d4e
Show file tree
Hide file tree
Showing 132 changed files with 5,858 additions and 5,852 deletions.
1 change: 1 addition & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ ktlint_standard_function-signature = disabled
[{*.kt,*.kts}]
indent_style = space
max_line_length = 140
indent_size = 2
ij_kotlin_code_style_defaults = KOTLIN_OFFICIAL
ij_continuation_indent_size = 2
ij_kotlin_allow_trailing_comma = false
Expand Down
5 changes: 5 additions & 0 deletions detekt.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ console-reports:
output-reports:
active: false

formatting:
Indentation:
active: true
indentSize: 2

comments:
active: true
AbsentOrWrongFileLicense:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,79 +29,79 @@ import stove.ktor.example.domain.JediService
import java.time.Duration

fun main(args: Array<String>) {
run(args)
run(args)
}

fun run(
args: Array<String>,
applicationOverrides: () -> Module = { module { } }
args: Array<String>,
applicationOverrides: () -> Module = { module { } }
): ApplicationEngine {
val applicationEngine =
embeddedServer(Netty, port = 8080, host = "0.0.0.0") {
mainModule(args, applicationOverrides)
}
applicationEngine.start(wait = false)
val applicationEngine =
embeddedServer(Netty, port = 8080, host = "0.0.0.0") {
mainModule(args, applicationOverrides)
}
applicationEngine.start(wait = false)

return applicationEngine
return applicationEngine
}

@Serializable
data class UpdateJediRequest(val name: String)

fun Application.mainModule(
args: Array<String>,
applicationOverrides: () -> Module
args: Array<String>,
applicationOverrides: () -> Module
) {
install(CallLogging) {
}
install(CallLogging) {
}

install(ContentNegotiation) {
json()
}
install(ContentNegotiation) {
json()
}

install(Koin) {
SLF4JLogger()
modules(
dataModule(args),
applicationModule(),
applicationOverrides()
)
}
install(Koin) {
SLF4JLogger()
modules(
dataModule(args),
applicationModule(),
applicationOverrides()
)
}

routing {
post("/jedis/{id}") {
val id = call.parameters["id"]!!.toLong()
try {
val request = call.receive<UpdateJediRequest>()
call.get<JediService>().update(id, request)
call.respond(HttpStatusCode.OK)
} catch (ex: Exception) {
ex.printStackTrace()
call.respond(HttpStatusCode.BadRequest)
}
}
routing {
post("/jedis/{id}") {
val id = call.parameters["id"]!!.toLong()
try {
val request = call.receive<UpdateJediRequest>()
call.get<JediService>().update(id, request)
call.respond(HttpStatusCode.OK)
} catch (ex: Exception) {
ex.printStackTrace()
call.respond(HttpStatusCode.BadRequest)
}
}
}
}

fun dataModule(args: Array<String>) =
module {
val map = args.associate { it.split("=")[0] to it.split("=")[1] }
single {
val builder =
PostgresqlConnectionConfiguration.builder().apply {
host(map["database.host"]!!)
database(map["database.databaseName"]!!)
port(map["database.port"]!!.toInt())
password(map["database.password"]!!)
username(map["database.username"]!!)
}
PostgresqlConnectionFactory(builder.connectTimeout(Duration.ofSeconds(10)).build())
module {
val map = args.associate { it.split("=")[0] to it.split("=")[1] }
single {
val builder =
PostgresqlConnectionConfiguration.builder().apply {
host(map["database.host"]!!)
database(map["database.databaseName"]!!)
port(map["database.port"]!!.toInt())
password(map["database.password"]!!)
username(map["database.username"]!!)
}
PostgresqlConnectionFactory(builder.connectTimeout(Duration.ofSeconds(10)).build())
}
}

fun applicationModule() =
module {
singleOf(::JediRepository)
singleOf(::JediService)
singleOf(::MutexLockProvider) { bind<LockProvider>() }
}
module {
singleOf(::JediRepository)
singleOf(::JediService)
singleOf(::MutexLockProvider) { bind<LockProvider>() }
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,25 @@ import kotlinx.coroutines.sync.Mutex
import java.time.Duration

interface LockProvider {
suspend fun acquireLock(
name: String,
duration: Duration
): Boolean
suspend fun acquireLock(
name: String,
duration: Duration
): Boolean

suspend fun releaseLock(name: String)
suspend fun releaseLock(name: String)
}

class MutexLockProvider : LockProvider {
private val mutex = Mutex()
private val mutex = Mutex()

override suspend fun acquireLock(
name: String,
duration: Duration
): Boolean {
return mutex.tryLock(this)
}
override suspend fun acquireLock(
name: String,
duration: Duration
): Boolean {
return mutex.tryLock(this)
}

override suspend fun releaseLock(name: String) {
mutex.unlock(this)
}
override suspend fun releaseLock(name: String) {
mutex.unlock(this)
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package stove.ktor.example.domain

data class Jedi(
val id: Long,
var name: String
val id: Long,
var name: String
)
Original file line number Diff line number Diff line change
Expand Up @@ -7,32 +7,32 @@ import kotlinx.coroutines.reactive.awaitFirstOrNull
import kotlinx.coroutines.reactive.awaitSingle

class JediRepository(private val postgresqlConnectionFactory: PostgresqlConnectionFactory) {
private lateinit var connection: PostgresqlConnection
private lateinit var connection: PostgresqlConnection

suspend fun findById(id: Long): Jedi {
return connection.createStatement("SELECT * FROM Jedis WHERE id=$id").execute().awaitFirst().map { r, rm ->
Jedi(
(r.get(Jedi::id.name, rm.getColumnMetadata(Jedi::id.name).javaType!!) as Int).toLong(),
r.get(Jedi::name.name, rm.getColumnMetadata(Jedi::name.name).javaType!!) as String
)
}.awaitSingle()
}
suspend fun findById(id: Long): Jedi {
return connection.createStatement("SELECT * FROM Jedis WHERE id=$id").execute().awaitFirst().map { r, rm ->
Jedi(
(r.get(Jedi::id.name, rm.getColumnMetadata(Jedi::id.name).javaType!!) as Int).toLong(),
r.get(Jedi::name.name, rm.getColumnMetadata(Jedi::name.name).javaType!!) as String
)
}.awaitSingle()
}

suspend fun update(jedi: Jedi) {
connection.createStatement("UPDATE Jedis SET ${Jedi::name.name}=('${jedi.name}') WHERE ${Jedi::id.name}=${jedi.id}")
.execute()
.awaitFirstOrNull()
}
suspend fun update(jedi: Jedi) {
connection.createStatement("UPDATE Jedis SET ${Jedi::name.name}=('${jedi.name}') WHERE ${Jedi::id.name}=${jedi.id}")
.execute()
.awaitFirstOrNull()
}

suspend fun transaction(invoke: suspend (JediRepository) -> Unit) {
connection = this.postgresqlConnectionFactory.create().awaitFirst()
connection.beginTransaction().awaitFirstOrNull()
try {
invoke(this)
connection.commitTransaction().awaitFirstOrNull()
} catch (ex: Exception) {
connection.rollbackTransaction().awaitFirstOrNull()
throw ex
}
suspend fun transaction(invoke: suspend (JediRepository) -> Unit) {
connection = this.postgresqlConnectionFactory.create().awaitFirst()
connection.beginTransaction().awaitFirstOrNull()
try {
invoke(this)
connection.commitTransaction().awaitFirstOrNull()
} catch (ex: Exception) {
connection.rollbackTransaction().awaitFirstOrNull()
throw ex
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,25 @@ import stove.ktor.example.UpdateJediRequest
import java.time.Duration

class JediService(private val repository: JediRepository, private val lockProvider: LockProvider) {
suspend fun update(
id: Long,
request: UpdateJediRequest
) {
val acquireLock = lockProvider.acquireLock(::JediService.name, Duration.ofSeconds(30))
suspend fun update(
id: Long,
request: UpdateJediRequest
) {
val acquireLock = lockProvider.acquireLock(::JediService.name, Duration.ofSeconds(30))

if (!acquireLock) {
print("lock could not be acquired")
return
}
if (!acquireLock) {
print("lock could not be acquired")
return
}

try {
repository.transaction {
val jedi = it.findById(id)
jedi.name = request.name
it.update(jedi)
}
} finally {
lockProvider.releaseLock(::JediService.name)
}
try {
repository.transaction {
val jedi = it.findById(id)
jedi.name = request.name
it.update(jedi)
}
} finally {
lockProvider.releaseLock(::JediService.name)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,44 +10,44 @@ import io.kotest.matchers.shouldBe
import stove.ktor.example.UpdateJediRequest

class ExampleTest : FunSpec({
data class JediTestAssert(
val id: Long,
val name: String
)
data class JediTestAssert(
val id: Long,
val name: String
)

test("should save jedi") {
TestSystem
.validate {
val givenId = 10
val givenName = "Luke Skywalker"
postgresql {
shouldExecute(
"""
test("should save jedi") {
TestSystem
.validate {
val givenId = 10
val givenName = "Luke Skywalker"
postgresql {
shouldExecute(
"""
DROP TABLE IF EXISTS Jedis;
CREATE TABLE IF NOT EXISTS Jedis (
id serial PRIMARY KEY,
name VARCHAR (50) NOT NULL
);
""".trimIndent()
)
shouldExecute("INSERT INTO Jedis (id, name) VALUES ('$givenId', 'Obi Wan Kenobi')")
}
http {
postAndExpectBodilessResponse(
"/jedis/$givenId",
body = UpdateJediRequest(givenName).some(),
token = None
) { actual ->
actual.status shouldBe 200
}
}
""".trimIndent()
)
shouldExecute("INSERT INTO Jedis (id, name) VALUES ('$givenId', 'Obi Wan Kenobi')")
}
http {
postAndExpectBodilessResponse(
"/jedis/$givenId",
body = UpdateJediRequest(givenName).some(),
token = None
) { actual ->
actual.status shouldBe 200
}
}

postgresql {
shouldQuery<JediTestAssert>("Select * FROM Jedis WHERE id=$givenId") {
it.count() shouldBe 1
it.first().name shouldBe givenName
}
}
}
}
postgresql {
shouldQuery<JediTestAssert>("Select * FROM Jedis WHERE id=$givenId") {
it.count() shouldBe 1
it.first().name shouldBe givenName
}
}
}
}
})
Loading

0 comments on commit d4a7d4e

Please sign in to comment.