-1

I am working on a NODE JS project with Typescript started by other people and I need to trigger an action if the response from some endpoints is successful, so I need to intercept this response before it is sent to the entity that is making the request.

The request is made, first it goes through anothers middlewares, then it goes to the controller, when it finishes, I need to catch it.

The way the responses are returned from controllers is this

return response.status(200).json(data);

How can I solve this issue?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
doDDy
  • 75
  • 7
  • Why intercept it? Why not just fix the code that sends the response or design it so that the logic for the response is where the response is being sent. You shouldn't have to be outside the code sending the response and trying to hack into it. – jfriend00 Jun 02 '22 at 06:26
  • If you are OK allowing the existing response to be sent and you just want to know when the response is done, you can just listen for an event on the `res` object. – jfriend00 Jun 02 '22 at 06:26
  • You could overwrite the `response.json` function in a middleware function like this `response._json = response.json; response.json = function(data){ /* do what you need here and then call */ response._json(data); }` – Molda Jun 02 '22 at 06:29
  • @jfriend00 I wont modify the response. I need to catch the status, and do other thing from there. There are a lot of endpoints, and I thought that do it manually in each one was not the best approach. – doDDy Jun 02 '22 at 06:58

1 Answers1

1

You can add some middleware BEFORE any of your request handlers that send a response that monitors the finish event on the response stream object to track when the request is done:

app.use((req, res, next) => {
    // listen for when the request is done
    res.on('finish', () => {
        console.log(`request for ${req.url} finished with status ${res.statusCode}`);
    });
    next();
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979