Skip to content

Instantly share code, notes, and snippets.

@talenguyen
Last active November 26, 2019 03:16
Show Gist options
  • Save talenguyen/bd18cc32767695920caf0160352bfec0 to your computer and use it in GitHub Desktop.
Save talenguyen/bd18cc32767695920caf0160352bfec0 to your computer and use it in GitHub Desktop.
Implementation of ExpressJS Middleware functions for Kotlin.
typealias Next<A, R> = (param: A) -> R
typealias Middleware<A, R> = (param: A, next: Next<A, R>) -> R
private class NextImpl<A, R>(
private val middleware: Middleware<A, R>,
private val next: Next<A, R>
) : Next<A, R> {
override fun invoke(param: A): R {
return middleware(param, next)
}
}
fun <A, R> applyMiddlewares(next: Next<A, R>, middlewares: List<Middleware<A, R>>): Next<A, R> {
return middlewares.foldRight(next, { middleware, acc -> NextImpl(middleware, acc) })
}
@talenguyen
Copy link
Author

Middleware functions can perform the following tasks:

  • Execute any code.
  • Make changes to the input and the output objects.
  • End the input-output cycle.
  • Call the next middleware function in the stack.

If the current middleware function does not end the input-output cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment