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

efemoney

08/31/2020, 3:08 AM
Hey everyone, I’m wondering, will this do what I believe it will do?
Copy code
/**
 * Compose multiple pipeline [interceptors] into one. This executes [interceptors] in a new pipeline running in this
 * interceptors context on this interceptors subject
 *
 * @return A [PipelineInterceptor] that executes other [interceptors] in a pipeline within its own context on its own subject
 * @param interceptors [PipelineInterceptor]s to execute **serially**
 */
fun <TSubject : Any, TContext : Any> compose(
  vararg interceptors: PipelineInterceptor<TSubject, TContext>
): PipelineInterceptor<TSubject, TContext> = {
  val pipeline = Pipeline(PipelinePhase("Compose"), interceptors.asList())
  pipeline.execute(context, subject)
}
with usage:
Copy code
route("/api") {
  get("/comics", GetAllComics)
  get("/comics/{page}", GetComicPage)
  get("/comics/latest", GetComicLatest)
  put("/users/token", compose(AuthenticateUser, SaveUserToken))
  put("/users/page", compose(AuthenticateUser, SaveUserPage))
}
I am trying to get the same behavior as nodejs’s
express
interceptors.
j

Jorge R

08/31/2020, 8:56 AM
Hi @efemoney, why are you doing all of this at the route layer/level? Why don't you use some architecture or apply some layers to reuse code? I would avoid logic in route definition. You don't need to use compose if you place your business logic in a different layer, if I'm understanding correctly what you are trying to do
e

efemoney

08/31/2020, 5:27 PM
I want some routes to be authenticated and others not. And I want the handling of that authenticated route to be in a central location.
j

Jorge R

09/01/2020, 1:30 PM
But you can add your routes to an authenticated section, and define authentication as you want. Check the following gist: https://gist.github.com/mathias21/c4361419b8738944ab19ab2729ca6893
e

efemoney

09/01/2020, 4:24 PM
Yeah I know that and I have a route already using that authentication but this is still something I’m trying to achieve and might come in handy later.