kreteshq / kretes

A Programming Environment for TypeScript & Deno
https://kretes.dev/
Other
676 stars 35 forks source link

Is it possible to add custom middlewares? #78

Closed emilos closed 3 years ago

emilos commented 4 years ago

Let's assume that I'd like to add a custom middleware, something similar to:

module.exports = function middleware (request) {
  request.language = deduceLanguage(request.url)
}

It's not ideal, because it's mutating the request, but at least easy to use and you wouldn't need to check the language everywhere.

Any thoughts?

zaiste commented 4 years ago

@emilos Handlers allow for functional composition. Here's a good example of that. You can combine multipe functionalities and pass it as array in a particular route.

Or, you can use the .use API and add a global middleware. There is a built in serve and security middleware.

I'm not sure if that responds to your question.

emilos commented 4 years ago

Thanks, it does! I'll leave this open for now, will add some docs about being able to use .use

emilos commented 4 years ago

I've pushed a PR https://github.com/huncwotjs/huncwot/pull/79. I was able to add a middleware inside of the library itself, but how can I do it inside of the app?

As far as I've investigated huncwot new creates a new app. The new app runs huncwot server which creates new Huncwot instance. It seems there is no access to the app instance, so I cannot add a middleware. Am I missing anything?

It might be necessary to expose it somehow or have a loading convention/directory for middlewares (if I understand the problem correctly).

zaiste commented 3 years ago

Global middlewares can be specified in config/server/middlewares.ts. It's a list that defines their execution from top to bottom. It's described here: https://kretes.dev/docs/guide/in-depth/routing/#reusable-workflows-middlewares