Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SailsJS : How to convert camel case to snake case in JSON response implicitly?

Is there a way in sails.js to convert camelCase to snake_case while returning the JSON response using res.ok(data), where data is an object, without having explicit getters or setters in the model to do this?

like image 996
Jaseem Abbas Avatar asked Sep 26 '22 11:09

Jaseem Abbas


1 Answers

There is also another solution that don't need to be implemented in each response.

You can define your custom hook in api/hooks folder with following content:

var snakeCase = require('snake-case');

module.exports = function (sails) {
  return {
    routes: {
      after: {
        'all /*': function overrideJsonx(req, res, next) {
          var jsonx = res.jsonx;
          res.jsonx = function (obj) {
            var res = snakeCase(obj);
            jsonx(res);
          };

          next();
        }
      }
    }
  }
};

It will work for all responses without modifying custom responses in api/response folder.

like image 136
Eugene Obrezkov Avatar answered Oct 11 '22 06:10

Eugene Obrezkov