Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
gaochengyidlmu opened this issue Jun 27, 2019 · 1 comment

Comments

@gaochengyidlmu
Copy link

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
Copy link
Author

在 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 数量。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant