Repository navigation
Do after response work #1981
|
I've been considering migrating from ExpressJS to KoaJS and while I've gotten just about everything ironed out, there's one last question that I'm not sure what the best practice is. There's a few times in my application that I need to trigger additional work, but it can be somewhat long running so I return the response to the user prior to doing so, but there doesn't seem to be an obvious best practice way to do so in KoaJS. For simplicity, here's one example:
Within KoaJS, it seems there's really only one way to do this, and that would be to turn off KoaJS's response for this endpoint, handle it myself, then do my after response work. But the docs seem to indicate that this is a really bad idea and may break KoaJS, so it seems irresponsible to do that. It did seem promising that the entire So is there a better way to do what I want? If not, would a pull request be acceptable to add lifecycle events on the Thanks a ton for the awesome library, hope we can find a solution! |
Replies: 1 comment
|
Actually looking further into it, I think I've found the perfect solution! I totally forgot that the NodeJS Response object itself already has lifecycle hooks. So I can hook into those to do what I want, such as: ctx.res.on("finish", async () => {
// You MUST use `res` not `response` to get the NodeJS object, rather than the KoaJS object
// But now here you can do all your after response work, and if defined where you already have a `ctx` you'll still have it
});Just tested it out and it seems to work exactly as I'd hope, retaining the context object and executing after the user gets the request, so we are good to go! |
Actually looking further into it, I think I've found the perfect solution!
I totally forgot that the NodeJS Response object itself already has lifecycle hooks. So I can hook into those to do what I want, such as:
Just tested it out and it seems to work exactly as I'd hope, retaining the context object and executing after the user gets the request, so we are good to go!