瀏覽代碼

create verifyBody middleware factory to abstract request validation

production
Jack Foltz 5 年之前
父節點
當前提交
740c153093
簽署人: foltik <jack@foltz.io> GPG Key ID: 303F88F996E95541
共有 1 個文件被更改,包括 23 次插入0 次删除
  1. +23
    -0
      app/util/verifyBody.js

+ 23
- 0
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;

Loading…
取消
儲存