mirror of
https://github.com/Foltik/Shimapan
synced 2025-01-05 15:58:03 -05:00
create verifyBody middleware factory to abstract request validation
This commit is contained in:
parent
9227fa428d
commit
740c153093
23
app/util/verifyBody.js
Normal file
23
app/util/verifyBody.js
Normal file
@ -0,0 +1,23 @@
|
||||
|
||||
// Verifies the request body is well formed
|
||||
// expectedProps follows the format:
|
||||
// [{name: 'myList', instance: 'Array'}, {name: 'myVar', type: 'string', optional: true}, etc.]
|
||||
const verifyBody = expectedProps =>
|
||||
(req, res, next) => {
|
||||
for (let i = 0; i < expectedProps.length; i++) {
|
||||
const expected = expectedProps[i];
|
||||
const prop = req.body[expected.name];
|
||||
|
||||
if (!expected.optional && !prop)
|
||||
return res.status(400).json({message: expected.name + ' not specified.'});
|
||||
|
||||
if (expected.type && typeof prop !== expected.type)
|
||||
return res.status(400).json({message: expected.name + ' malformed.'});
|
||||
|
||||
if (expected.instance && !(prop instanceof expected.instance))
|
||||
return res.status(400).json({message: expected.name + ' malformed.'});
|
||||
}
|
||||
next();
|
||||
};
|
||||
|
||||
module.exports = verifyBody;
|
Loading…
Reference in New Issue
Block a user