Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom response interceptors. #140

Open
vasuvanka opened this issue Feb 19, 2018 · 2 comments
Open

Custom response interceptors. #140

vasuvanka opened this issue Feb 19, 2018 · 2 comments

Comments

@vasuvanka
Copy link

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

@etsuo
Copy link
Member

etsuo commented Feb 20, 2018

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
Copy link
Member

etsuo commented Feb 20, 2018

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants