Skip to content

Instantly share code, notes, and snippets.

@DesignByOnyx
Created February 28, 2017 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DesignByOnyx/e38fb3983e50b6f7c097ea4863a58073 to your computer and use it in GitHub Desktop.
Save DesignByOnyx/e38fb3983e50b6f7c097ea4863a58073 to your computer and use it in GitHub Desktop.
Express middleware for coercing form-urlencoded data into primitive counterparts
'use strict';
/**
* This file is useful for x-www-form-urlencoded requests where all data is a string.
* If the request uses application/json, this middleware is not needed.
* This loops over all of the data and converts strings to their primitive form,
* basically normalizing numbers, booleans, and null/undefined/'' values.
* This could potentially have side effects, though none were encountered after
* months of using this middleware on a busy project.
*/
const REG_METHOD_WITH_BODY = /^(?:put|patch|post)$/;
function isObject(val) {
return val.constructor === Object;
}
function isNumber(val) {
return !isNaN(parseFloat(val)) && isFinite(val);
}
function isBoolean(val) {
return val === 'false' || val === 'true';
}
function isArray(val) {
return Array.isArray(val);
}
function parseObject(obj) {
var result = {};
var key;
for (key in obj) {
result[key] = parseValue(obj[key]);
}
return result;
}
function parseArray(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
result[i] = parseValue(arr[i]);
}
return result;
}
function parseNumber(val) {
return Number(val);
}
function parseBoolean(val) {
return val === 'true';
}
function parseValue(val) {
if (typeof val === 'undefined' || ('' + val) === 'null' || val === '') {
return null;
} else if (isBoolean(val)) {
return parseBoolean(val);
} else if (isArray(val)) {
return parseArray(val);
} else if (isObject(val)) {
return parseObject(val);
} else if (isNumber(val)) {
return parseNumber(val);
} else {
return val;
}
}
module.exports = () => {
return function(req, res, next) {
if (REG_METHOD_WITH_BODY.test(req.method.toLowerCase()) && req.get('Content-Type') !== 'application/json') {
req.body = parseValue(req.body);
}
next();
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment