Created
May 13, 2023 17:11
-
-
Save partapparam/024c70581a91e18b0af958bc49758c72 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Express Middleware built to convert all incoming request body data to snake_case | |
// Requires npm install lodash | |
const { snakeCase } = require("lodash") | |
const snakeCaseKeys = (data) => { | |
// check to see if req.body is an array. | |
if (Array.isArray(data)) { | |
// if Array, map() through all objects in Array. | |
return data.map((object) => snakeCaseKeys(object)) | |
} else if (data !== null && data.constructor === Object) { | |
return Object.keys(data).reduce( | |
(result, key) => ({ | |
...result, | |
[toSnakeCase(key)]: snakeCaseKeys(data[key]), | |
}), | |
{} | |
) | |
} | |
return data | |
} | |
const toSnakeCase = (str) => snakeCase(str) | |
// Middleware. Map through req.body and call next() | |
const convertToSnakeCase = (req, res, next) => { | |
// before | |
console.log(req.body) | |
req.body = snakeCaseKeys(req.body) | |
// after | |
console.log(req.body) | |
next() | |
} | |
module.exports = convertToSnakeCase |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment