Backend Middleware

2018-12-09 08:34:22

Flexible use of middleware mechanism can effectively extend the functions of the architecture. The main functions of middleware are interception, reorganization, injection

  1. interception:For example, judging user privileges through middleware and suspending subsequent execution if no privileges exist
  2. reorganization:For example, the data sent from the frontend is validated by middleware and transformed into the desired type
  3. injection:For example, injecting objects into ctx through middleware to provide the necessary basic functionality for subsequent code

Here, through a virtual requirement, we use middleware to achieve three functions: interception',reorganization’ and `injection’:

  1. Following the previous code, the frontend sends two parameters to the backend: message, markCount
  2. interception:The middleware determines whether message is empty, and if it is empty, terminates subsequent execution
  3. reorganization:Mandatory conversion of markCount type to Integer type
  4. injection:Inject a method to be called in subsequent code

Declaration of Middleware


// middlewares
config.middlewares = {
  middlewareDemo: {
    global: false,
    dependencies: 'instance',
name description
global Whether global middleware or not, the global middleware will be loaded automatically, and the local middleware needs to be specified manually
dependencies Indicate which middlewares this middleware relies on to load after those middlewares. Generally, it depends on middleware instance, because middleware instance provides the basic logic of multi-instance

Definition of Middleware


module.exports = options => {
  return async function middlewareDemo(ctx, next) {
    // check message
    if (!ctx.request.body.message) ctx.throw(406);
    // adjust markCount
    ctx.request.body.markCount = parseInt(ctx.request.body.markCount);
    // inject function
    if (!ctx.meta) ctx.meta = {};
    ctx.meta._demoFunction = function() {
      const { message, markCount } = ctx.request.body;
      return `${message}${new Array(markCount + 1).join('!')}`;
    // next
    await next();

Reference Middleware


const demo = require('./middleware/demo.js');

module.exports = {
  middlewareDemo: demo,

Usage of Middleware

Because middlewareDemo is a local middleware, you need to specify it manually on the API route


// test
- { method: 'post', path: 'test/echo', controller: test, middlewares: 'transaction' },
+ { method: 'post', path: 'test/echo', controller: test, middlewares: 'transaction,middlewareDemo' },

Backend Logic


async echo() {
  const res = this.ctx.meta._demoFunction();