core icon indicating copy to clipboard operation
core copied to clipboard

Custom response interceptors.

Open vasuvanka opened this issue 8 years ago • 2 comments

There is should be a way to get the custom response for every API instead of fixed.

vasuvanka avatar Feb 19 '18 10:02 vasuvanka

Generically (i.e., raw express), it might be done something like this:

const express = require('express');
const app = express();

app.all('*', (req, res, next) => {
  var json = res.json;
  res.json = function (data) {
    const result = {
      ...data,
      inserted: 1
    };
    json.call(this, result);
  };
  next();
});

app.use('/endpoint', (req, res, next) => {
  res.json({
    result: 1
  });
  next();
});

app.use((req, res) => {
  if (!res.headersSent)
    res.status(404).json({error: 'NOT_FOUND'});
});

app.listen(3000, () => console.log('Example app listening on port 3000!'));

I included the 404 handler because there's a problem here that's surfaced.

If I GET /endpoint the response code is 200 with body:

{
    "result": 1,
    "inserted": 1
}

However, if I get an invalid URL, GET /invalid, the response code is properly 404, but the body ran through the catch all interceptor:

{
    "error": "NOT_FOUND",
    "inserted": 1
}

etsuo avatar Feb 20 '18 00:02 etsuo

Note to self - the * interceptor pattern used above might be a way to refactor how resLocals works so that the route handlers don't have to call next unless they implement an after or afterAll handler.

etsuo avatar Feb 20 '18 00:02 etsuo