Hello :wave: What is the proper way to create Ktor...
# ktor
d
Hello 👋 What is the proper way to create Ktor server plugin that also auto-configures routes? i.e. https://ktor.io/docs/custom-plugins-base-api.html#create mentions
BaseApplicationPlugin
that accepts a pipeline (e.g.
ApplicationCallPipeline
) and
BaseRouteScopedPlugin
which should be applied to a specific route. Should I just use
Application
which extends
ApplicationCallPipeline
?
a
Do you need to add some routes or write a plugin which can be applied to a route?
r
I just use a
Routing.setupMyPlugin(…)
function as entry point for this kind of libraries
Even if there was a way, your plugin could be installed before the
Routing
plugin, how could you add a route then?
d
👋 I'm new to ktor hence asking. I just started looking into our feature request -> https://github.com/ExpediaGroup/graphql-kotlin/issues/1471 TLDR expectation is plugin would accept user configuration (ie which queries are supported) to create GraphQL server accepting requests on some specified routes (ie /graphql)
Ktor docs (and examples) talk about some very basic stuff like adding a header or logging requests. Was wondering what is the recommendation for application level plugins that process incoming requests
ie asking all folks to implement the same routes in their apps seems like a bad experience
r
Can't you do something like
Application.pluginOrNull(Routing)
and add routes like that? I don't remember if a plugin can access the app but I think it can?
d
Thats why I'm asking :)
Application
extends
ApplicationCallPipeline
So I can access the app in configure function
r
Copy code
val MyTestPlugin = createApplicationPlugin("MyTestPlugin") {
        
        application.plugin(Routing).run { 
            
            get("/") { call.respond("Hello world") }
            
        }
        
    }
👍 1
You would add some error handling when
Routing
isn't setup before your plugin but it should just work
d
👍 sounds good
r
application.pluginOrNull(Routing) ?: error("MyTestPlugin requires Routing plugin to be setup before")
or something
👍 2
d
btw ktor already exposes this (which I'm going to use) ->
Copy code
public fun Application.routing(configuration: Routing.() -> Unit): Routing =
    pluginOrNull(Routing)?.apply(configuration) ?: install(Routing, configuration)
r
What if the user installs your plugin then installs Routing using
install(Routing)
afterwards?
d
user error I guess