Skip to content

Instantly share code, notes, and snippets.

@partapparam
Created May 13, 2023 17:11
Show Gist options
  • Save partapparam/024c70581a91e18b0af958bc49758c72 to your computer and use it in GitHub Desktop.
Save partapparam/024c70581a91e18b0af958bc49758c72 to your computer and use it in GitHub Desktop.
// 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