baijijs / baiji

A powerful and customizable Rest API framework built on top of express, supports validations, sanitizers, api presenters e.g.
MIT License
16 stars 3 forks source link

如果没有 beforeRespond 的 hook,在 ctx.done 时,不会返回数据 #3

Open gaochengyidlmu opened 5 years ago

gaochengyidlmu commented 5 years ago
const baiji = require('./index.js');
const app = baiji('my-example-app');

class UsersCtrl extends baiji.Controller {
  constructor() {
    super();
  }

  initConfig() {
    return {
      search: {
        description: 'Search users...',
        route: { path: '/', verb: 'get' }
      }
    };
  }

  search(ctx, next) {
    ctx.done([{ username: 'lyfeyaj', gender: 1 }], next);
  }
}

// Use express middleware: response-time
app.use(require('response-time')());
// Use express middleware: cookie-parser
app.use(require('cookie-parser')());
// Use controller
app.use(UsersCtrl);

// Start app and listen on port 3000
app.listen(3000, () => {
  console.log('server is running at 3000');
});

调用时,返回的是空数据。

在 lib/contexts/express.js 92 行,data = await this.action.invokeBeforeRespond(ctx); 重新赋值 data 后,值为 undefined

gaochengyidlmu commented 5 years ago

在 lib/Action.js 240 compose 方法中,给 beforeRespond 添加默认处理方式:

  compose(hooks) {
    hooks = hooks || {};

    let stack = []
      .concat(this.skipHooks ? [] : (hooks.before || []))
      .concat(this.handler)
      .concat(this.skipHooks ? [] : (hooks.after || []));

    let errorHandler = utils.compose(hooks.error || []);

    this.stack = utils.compose(stack, errorHandler);

    hooks.beforeRespond = hooks.beforeRespond || [];
    if (hooks.beforeRespond.length === 0) hooks.beforeRespond.push((ctx) => ctx.result);

    this.beforeRespondStack = utils.compose(hooks.beforeRespond, errorHandler);
  }

或者在 229 行的 invokeBeforeRespond 中判断 beforeRespond 的 hook 数量。