Skip to content

Instantly share code, notes, and snippets.

@singh1114
Last active January 25, 2021 20:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save singh1114/766113f61c4f61b8357e4ff0223ec3c1 to your computer and use it in GitHub Desktop.
Save singh1114/766113f61c4f61b8357e4ff0223ec3c1 to your computer and use it in GitHub Desktop.
Node.js middleware article
const validateParams = function (requestParams) {
return function (req, res, next) {
for (let param of requestParams) {
if (checkParamPresent(Object.keys(req.body), param)) {
let reqParam = req.body[param.param_key];
if (!checkParamType(reqParam, param)) {
return res.send(400, {
status: 400,
result: `${param.param_key} is of type ` +
`${typeof reqParam} but should be ${param.type}`
});
} else {
if (!runValidators(reqParam, param)) {
return res.send(400, {
status: 400,
result: `Validation failed for ${param.param_key}`
});
}
}
} else if (param.required){
return res.send(400, {
status: 400,
result: `Missing Parameter ${param.param_key}`
});
}
}
next();
}
};
const checkParamPresent = function (reqParams, paramObj) {
return (reqParams.includes(paramObj.param_key));
};
const checkParamType = function (reqParam, paramObj) {
const reqParamType = typeof reqParam;
return reqParamType === paramObj.type;
};
const runValidators = function (reqParam, paramObj) {
for (let validator of paramObj.validator_functions) {
if (!validator(reqParam)) {
return false
}
}
return true;
};
module.exports = {
validateParams: validateParams
};
@motdde
Copy link

motdde commented Jan 18, 2021

This is really cool, it took me a while to understand what the code is doing, but when I figured it out 😲

@singh1114
Copy link
Author

This is really cool, it took me a while to understand what the code is doing, but when I figured it out 😲

Thanks for the appreciation @motdde

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment