路由钩子是什么

模块a-hook提供了路由钩子机制,可以在后端API路由 执行前执行后处理业务逻辑

定义路由钩子

在模块的meta中定义路由钩子

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' },
  ],
},
名称 说明
before 执行前钩子
after 执行后钩子
path 需要钩的后端API路由
route 需要执行的后端API路由

定义钩子API路由

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 } } },

添加钩子逻辑

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;
};