Skip to content

Middleware

Hugo Persson edited this page Jan 22, 2021 · 3 revisions

Implementing middleware

You have three ways to declare middleware

Action specific middleware

Action specific middleware is only runned for the specific actions your declare it for, the syntax for this is

@addMiddleware([middleware1, middleware2...])

Controller specific middleware

Controller specific middleware is runned for every action in an controller, the controller specific middleware is an property of the base class Controller that is an array. To declare controller specific middleware use the following syntax¨

globalMiddleware = [middleware1, middleware2...];

Application specific middleware

Execution order

  1. Application specific middleware
  2. Controller specific middleware
  3. Action specefic middlware

Exiting action stack

If you wish to cancel the remaining functions in the middleware stack and the action function you can throw an error. The content of the error does not matter, you can throw an empty string, see following example

export function requiredAuthenction(controller: Controller) {
    if (!controller.authData) {
        controller.res.json({ error: true, message: "NoAuth" });
        throw "";
    }
}

Creating middleware

A middleware is a function that takes a controller as an argument, the function will be awaited if async, see following example of a async middleware

function aAsyncFunction(controller: Controller) {
    await somethingAsync();
   // do something more? 
}

Clone this wiki locally