From 740c153093e71197c8f7530795531f0158c4347c Mon Sep 17 00:00:00 2001 From: Jack Foltz Date: Sat, 28 Jul 2018 16:49:54 -0400 Subject: [PATCH] create verifyBody middleware factory to abstract request validation --- app/util/verifyBody.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 app/util/verifyBody.js diff --git a/app/util/verifyBody.js b/app/util/verifyBody.js new file mode 100644 index 0000000..236c029 --- /dev/null +++ b/app/util/verifyBody.js @@ -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; \ No newline at end of file