Arjan van Wieringen
04/27/2025, 7:14 AMcreateApplicationPlugin
/ createRouteScopedPlugin
are typically instantiated as values with a configuration block? In a lot of cases it is much easier to just do:
fun MyCustomPlugin(val myDeps: MyDeps) = createRouteScopedPlugin("MyCustomPlugin") {
...use myDeps
}
instead of a configuration class with mutable variables.simon.vergauwen
04/29/2025, 8:02 AMMyDeps
is a required parameter, so you avoid potentially forgetting `install(MyCustomPlugin) { deps = myDeps }`which is great!
Most plugins in Ktor itself are designed to work without any required parameters and therefor they have no need for that restriction. Two comparisons:
For example, falling back to env "OPENAI_TOKEN"
val OpenAi = createApplicationPlugin("OpenAi", { OpenAiConfiguratin.Builder() }) {
if(builder.apiKey == null) builder.apiKey(getenv("OPENAI_TOKEN"))
val config = pluginConfig.build()
}
Instead of:
fun OpenAi(token: String) = createApplicationPlugin("OpenAi", { OpenAiConfiguratin.Builder() }) {
val config = pluginConfig.apiKey(token).build()
}
Remember that if you want to be able to install 2 plugins you need to implement a custom plugin with different AttributeKey
.