What is Route Hook

The module a-hook provides a route hook mechanism, which can perform custom logic before or after the backend API route is executed

Definition of Route Hook

Define route hooks in the meta of the module

src/module/test-party/backend/src/meta.js

hook: {
  before: [
    { path: '/test/party/test/feat/hook/echo', route: 'test/feat/hook/echoBefore' },
  ],
  after: [
    { path: '/test/party/test/feat/hook/echo', route: 'test/feat/hook/echoAfter' },
  ],
},
Name Description
before before hook
after after hook
path the API route to be hooked
route the API route of hook to be performed

Definition of API Route of Route Hook

src/module/test-party/backend/src/routes.js

{ method: 'post', path: 'test/feat/hook/echo', controller: testFeatHook, middlewares: 'test', meta: { auth: { enable: false } } },
{ method: 'post', path: 'test/feat/hook/echoBefore', controller: testFeatHook, middlewares: 'test', meta: { auth: { enable: false } } },
{ method: 'post', path: 'test/feat/hook/echoAfter', controller: testFeatHook, middlewares: 'test', meta: { auth: { enable: false } } },

Route Hook Logic

src/module/test-party/backend/src/controller/test/feat/hook.js

const require3 = require('require3');
const assert = require3('assert');

module.exports = app => {

  class HookController extends app.Controller {

    async echo() {
      const data = this.ctx.request.body.data;
      assert.equal(data.text, 'before');
      data.text = 'before:echo';
      this.ctx.success();
    }

    async echoBefore() {
      const ctxCaller = this.ctx.ctxCaller;
      ctxCaller.request.body.data = { text: 'before' };
      this.ctx.success();
    }
    async echoAfter() {
      const ctxCaller = this.ctx.ctxCaller;
      const data = ctxCaller.request.body.data;
      assert.equal(data.text, 'before:echo');
      this.ctx.success();
    }

  }

  return HookController;
};