Skip to content

HTTP – Middlewares

Bartosz Łaniewski edited this page Mar 24, 2018 · 6 revisions

A middleware is a class which acts as a bridge between the initial request and the final route which sends a response back to the user. Our framework automatically initialises and populates each imported middleware. A typical data-flow looks as follows:

  • For Express.js:

    1. constructor({dependencyA, dependencyB});
    2. before(req, res, ...rest);
    3. handle(req, res, ...rest);
    4. after(req, res, ...rest);
  • For Koa.js:

    1. constructor({dependencyA, dependencyB});
    2. async before(ctx, next, ...rest);
    3. async handle(ctx, next, ...rest);
    4. async after(ctx, next, ...rest);

For example, consider the following middleware for Koa.js:

class AclMiddleware {
  constructor({models, logger}) {
    this.models = models;
    this.logger = logger;
  }
  
  async before(ctx) {
    if (!ctx.state.user) {
      ctx.throw(401, "Not allowed");
    }
  }
  
  async handle(ctx, next, permissions) {
    if (ctx.state.user.hasPermissions(permissions)) {
      return next();
    }
  }

  async after(ctx, next, permissions) {
    this.logger.info("…");
  }
}