1

I'm trying to decide on a consistent response JSON structure and I found this SO answer.

I like the simplicity of JSend but now I'm wondering what is a clean way to implement that structure in express without having to manually create it each response or use a constructor in every controller method to help build the structure. I found jsend-express npm but it has so few downloads I'm worried about relying on it.

Can anyone recommend some ways to automatically enforce some of this structure in express myself?

However, I'm not sure why a status key is even necessary when the 3 states seem to already be covered by HTTP statuses and I don't see this key recommended in google's style guide, so that's another reason I may not want to use the jsend package and just do it myself to omit some keys and add later if needed.

Neil M
  • 171
  • 8

1 Answers1

0

This ended up being how I did it based on this SO answer.

I have a catch all error handler that adds the error key, but for all non-errors I wanted the data to be wrapped in a data key without having do it in every controller method by hand, or to call another function in every controller method before the res.json since that is also repetitive.

/**
 * Nests all successful res data in a `data` key. Any additional meta-data
 * that needs to be present at the top level json object can be added here.
 * @param {request} _req
 * @param {response} res
 */
const modifyResponseBody = (_req, res, next) => {
  const resDotJson = res.json;

  res.json = function (data) {
    const isError = data?.hasOwnProperty?.("error") === true;

    if (!isError) {
      arguments[0] = { data: data };
    }

    resDotJson.apply(res, arguments);
  };
  next();
};

app.use(modifyResponseBody);
Neil M
  • 171
  • 8