【发布时间】:2019-12-08 11:11:40
【问题描述】:
Facebook messenger api 要求在我的服务器上收到 webhook 请求后,在 20 秒内立即发送 200 响应。这可能比其余中间件完成执行所需的时间更长,因此我先发送 200 响应,然后开始执行中间件以处理在 messenger 上发送回复等。
但是,这会破坏 Jest,因为在从 jest 模拟函数检索到响应后,中间件会继续输出到控制台。我无法想到使用 res.send() 发送多个响应,因为它在内部调用 res.close()。
这是正确的方法吗?我不应该立即发送 200 响应吗?有没有办法发送多个?
我尝试过使用 res.write(),但它不会立即发送响应。
private webhookEndpoint = async (req: express.Request, res: express.Response): Promise<any> => {
let body: MessageBodyRequest = req.body
if (
!isValidSHA1(
process.env.APP_SECRET as string,
JSON.stringify(req.body),
req.get('X-Hub-Signature') as string
)
) {
console.error("Invalid webhook signature")
return res.sendStatus(403);
}
// Checks this is an event from a page subscription
if (body.object === 'page') {
// Returns a '200 OK' response to all requests
res.status(200).send('EVENT_RECEIVED')
// Iterates over each entry - there may be multiple if batched
try {
//await triggers the try catch
return await Promise.all(body.entry.map(async (entry) => {
let message = entry.messaging[0] //will only ever have 1 message
console.log("message received: ", message)
let messageReceived = new MessageReceived(message)
return messageReceived.handle()
}))
} catch (error) {
console.error("Error handling incoming message: ", error)
}
} else {
// Returns a '404 Not Found' if event is not from a page subscription
return res.sendStatus(404)
}
}
【问题讨论】:
-
您也可以添加测试吗?另外,您的意思是因为继续执行而中断?因为如果那是行为,那么您也应该期望该控制台打印。
-
一个 HTTP 请求可以有多个“响应”,但响应都有 1xx 范围内的状态码,例如 102 处理中。 stackoverflow.com/a/53231701/395461
-
您的中间件在做什么,处理时间可能超过 20 秒?你能以某种方式减少它吗?
-
@Shannon 发送视频等事情需要很长时间才能等待
标签: node.js typescript express jestjs facebook-messenger-bot