1
0
mirror of https://github.com/Foltik/Shimapan synced 2024-11-10 23:53:31 -05:00
shimapan/app/util/verifyBody.js

36 lines
1.5 KiB
JavaScript
Raw Normal View History

2018-08-01 13:07:52 -04:00
// Verifies a single property is well formed
const verifyProp = (req, expected) => new Promise((resolve, reject) => {
const prop = req.body[expected.name];
2018-08-01 13:07:52 -04:00
if (!expected.optional && !prop)
return reject({code: 400, message: expected.name + ' not specified.'});
if (prop && expected.type && typeof prop !== expected.type)
return reject({code: 400, message: expected.name + ' malformed.'});
2018-08-01 13:07:52 -04:00
if (prop && expected.instance && !(prop instanceof expected.instance))
return reject({code: 400, message: expected.name + ' malformed.'});
2018-08-01 13:07:52 -04:00
if (prop && expected.maxLength && prop.length > expected.maxLength)
return reject({code: 422, message: expected.name + ' too long.'});
2018-08-01 13:07:52 -04:00
if (prop && expected.sanitize && req.sanitize(prop) !== prop)
return reject({code: 422, message: expected.name + ' contains invalid characters.'});
2018-08-01 13:07:52 -04:00
if (prop && expected.restrict && prop.replace(expected.restrict, '') !== prop)
return reject({code: 422, message: expected.name + ' contains invalid characters.'});
2018-08-01 13:07:52 -04:00
resolve();
});
2018-08-01 13:07:52 -04:00
// Verifies the entire 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) => {
Promise.all(expectedProps.map(expected => verifyProp(req, expected)))
.then(() => next())
.catch(err => res.status(err.code).json({message: err.message}));
};
module.exports = verifyBody;