express-humps
Version:
A middleware which can camelize the request body and decamelize the response through json method.
49 lines (39 loc) • 1.38 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.default = createMiddleware;
var _humps = require('humps');
var _humps2 = _interopRequireDefault(_humps);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* create a middleware to change json format from snake case to camelcase in request
* then change back to snake case in response
*
* @param {Object} options - humps options
*/
function createMiddleware(options) {
return function (req, res, next) {
/**
* camelize req.body
*/
if (req.body && _typeof(req.body) === 'object') {
req.body = _humps2.default.camelizeKeys(req.body, options);
}
/**
* camelize req.query
*/
if (req.query && _typeof(req.query) === 'object') {
req.query = _humps2.default.camelizeKeys(req.query, options);
}
/**
* wrap res.json()
*/
var sendJson = res.json;
res.json = function (data) {
return sendJson.call(res, _humps2.default.decamelizeKeys(data, options));
};
return next();
};
}