https://kotlinlang.org logo
#ktor
Title
# ktor
d

Dariusz Kuc

02/01/2023, 11:12 PM
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

Aleksei Tirman [JB]

02/02/2023, 8:26 AM
Do you need to add some routes or write a plugin which can be applied to a route?
r

ribesg

02/02/2023, 8:59 AM
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

Dariusz Kuc

02/02/2023, 2:20 PM
👋 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

ribesg

02/02/2023, 2:28 PM
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

Dariusz Kuc

02/02/2023, 2:28 PM
Thats why I'm asking :)
Application
extends
ApplicationCallPipeline
So I can access the app in configure function
r

ribesg

02/02/2023, 2:31 PM
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

Dariusz Kuc

02/02/2023, 2:32 PM
👍 sounds good
r

ribesg

02/02/2023, 2:32 PM
application.pluginOrNull(Routing) ?: error("MyTestPlugin requires Routing plugin to be setup before")
or something
👍 2
d

Dariusz Kuc

02/02/2023, 9:03 PM
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

ribesg

02/03/2023, 9:00 AM
What if the user installs your plugin then installs Routing using
install(Routing)
afterwards?
d

Dariusz Kuc

02/03/2023, 1:27 PM
user error I guess
25 Views