I just followed Discord's tutorial for hosting an application on a cloudflare worker. I'm trying to convert one of my bots but I've been having a problem for a few days now, I can't figure out how to use deffer reply. When I return my reply with type 5 (DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE) but after my request, my worker stops and the code that follows does not execute.
My question is how can I execute code after sending my response when I use cloudflare workers.
Here is my code:
// [...]
router.post('/', async (request, env) => {
const message = await request.json();
console.log(message);
if (message.type === InteractionType.APPLICATION_COMMAND) {
switch (message.data.name.toLowerCase()) {
case SETUP.name.toLowerCase(): {
sendDeferedReply(message, env); // Take a few seconds to run
return new JsonResponse({
type: 5,
})
}
});
});
// [...]
export default {
async fetch(request, env) {
if (request.method === 'POST') {
const signature = request.headers.get('x-signature-ed25519');
const timestamp = request.headers.get('x-signature-timestamp');
console.log(signature, timestamp, env.DISCORD_PUBLIC_KEY);
const body = await request.clone().arrayBuffer();
const isValidRequest = verifyKey(
body,
signature,
timestamp,
env.DISCORD_PUBLIC_KEY
);
if (!isValidRequest) {
console.error('Invalid Request');
return new Response('Bad request signature.', { status: 401 });
}
}
return router.handle(request, env);
},
};
Thank you in advance
CodePudding user response:
You can use waitUntil()
to schedule work that happens after the response. The runtime will wait up to 30 seconds after the response has been sent for waitUntil()
tasks to complete before tearing down the event context.
async fetch(request, env, ctx) {
// ...
ctx.waitUntil(someAsyncFunction());
return response;
}