Created
March 14, 2025 08:29
-
-
Save nomisRev/2d221f66406b2b6324fae51565b0d5b1 to your computer and use it in GitHub Desktop.
Ktor Koin KGraphQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.apurebase.kgraphql.GraphQL | |
import com.apurebase.kgraphql.schema.Publisher | |
import com.apurebase.kgraphql.schema.dsl.SchemaBuilder | |
import io.ktor.server.application.* | |
import org.koin.dsl.module | |
import org.koin.ktor.ext.inject | |
import org.koin.ktor.plugin.Koin | |
import org.koin.logger.slf4jLogger | |
import kotlin.getValue | |
fun main(args: Array<String>) { | |
io.ktor.server.netty.EngineMain.main(args) | |
} | |
// DI Setup | |
fun interface HelloService { | |
fun sayHello(): String | |
} | |
fun Application.module() { | |
install(Koin) { | |
slf4jLogger() | |
modules(module { | |
single<HelloService> { | |
HelloService { "Hello, World from the HelloService!" } | |
} | |
}) | |
} | |
configureGraphQL() | |
} | |
// GraphQL Setup | |
data class HelloMessage(val message: String) | |
fun Application.configureGraphQL() { | |
install(GraphQL) { | |
playground = true | |
schema { | |
hello(this) | |
mutation(this@configureGraphQL) | |
type<HelloMessage> { | |
description = "A hello message" | |
} | |
} | |
} | |
} | |
// Query, Mutation, Subscription builders | |
fun Application.hello(builder: SchemaBuilder): Publisher { | |
val helloService by inject<HelloService>() | |
return builder.query("hello") { | |
description = "Trigger the HelloService to say hello" | |
resolver { -> | |
val message = helloService.sayHello() | |
HelloMessage(message) | |
} | |
} | |
} | |
// Reversed order of parameters between SchemaBuilder <~> Application | |
fun SchemaBuilder.mutation(app: Application): Publisher { | |
// val dependency by app.inject<Dependency>() | |
return mutation("mutateSomething") { | |
description = "Mutates something" | |
resolver { input: String -> | |
println("Do something with $input") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment