【发布时间】:2020-03-11 13:20:29
【问题描述】:
我正在为我的应用程序中的 API 端点编写中间件,这些端点响应来自其他应用程序的 webhook,并且对 Koa 相对较新,因此并不完全熟悉它的模式。
我想按如下方式构建我的中间件:
exports.updateReceived = async (ctx, next) => {
// Respond to server issuing the webhook
ctx.res.body = "ok";
ctx.res.statusCode = 200;
// Grab what we need from the request
const { headers, state, request } = ctx;
const { body } = request;
// Do some async work
const { example } = await doSomeAsyncWork(ctx);
// Prepare a database query
const query = { aValue: anId };
// Run the DB query
const result = await Thing.findOne(query);
// Add data to the request
state.thing = result;
// Move on...
return next();
};
但是,这似乎不起作用,因为我的任何异步方法中的错误都可能导致路由出错。
我的目标是让这个端点总是(立即)响应“是的,好的”,这意味着它只是由应用程序来处理任何错误状态。
我对此进行了很好的研究,并且遇到了这种模式:
app.use(async ctx => {
db.fetch() // Assuming a Promise is returned
.then(() => { ... })
.catch(err => {
log(err)
})
// status 200 will be returned regardless of if db.fetch() resolves or rejects.
ctx.status = 200
})
但是,这不能满足我的需求,因为中间件没有使用next,所以据我所知,这并不是一个真正有用的模式。
谁能告诉我我忽略了什么?
【问题讨论】:
-
关键是你的中间件需要返回before调用next。接下来是中间件链的封装。