Facebook messenger api requires a 200 response be sent as soon as the webhook request is received on my server, within 20 seconds. This is potentially longer than the rest of the middleware needs to finish executing, so I send the 200 response first, then start executing middleware to handle sending a reply on messenger etc.
However, this breaks Jest, as the middleware continues to output to the console after the response is retrieved from the jest mock function. There is no way I can think of to send multiple responses with res.send(), as that calls res.close() internally.
Is this the correct approach? Should I not be sending the 200 response instantly? Is there a way to send multiple?
I have tried using res.write(), but that does not send the response instantly.
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)
}
}