Skip to content

Commit

Permalink
feat: added checkRequired middleware for API calls
Browse files Browse the repository at this point in the history
  • Loading branch information
julianlam committed Oct 8, 2020
1 parent fd67355 commit 7b6d43b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
11 changes: 11 additions & 0 deletions src/middleware/index.js
Expand Up @@ -237,3 +237,14 @@ middleware.validateAuth = helpers.try(async function validateAuth(req, res, next
next(err);
}
});

middleware.checkRequired = function (fields, req, res, next) {
// Used in API calls to ensure that necessary parameters/data values are present
const missing = fields.filter(field => !req.body.hasOwnProperty(field));

if (!missing.length) {
next();
}

controllers.helpers.formatApiResponse(400, res, new Error('Required parameters were missing from this API call: ' + missing.join(', ')));
};
7 changes: 1 addition & 6 deletions src/routes/write/users.js
Expand Up @@ -15,12 +15,7 @@ const helpers = require('../../controllers/helpers');
module.exports = function () {
var app = require('express').Router();

app.post('/', middleware.authenticate, middleware.isAdmin, async (req, res) => {
helpers.checkRequired(['username'], req, res);
// if (!utils.checkRequired(['username'], req, res)) {
// return false;
// }

app.post('/', middleware.checkRequired.bind(null, ['username']), middleware.authenticate, middleware.isAdmin, async (req, res) => {
const uid = await users.create(req.body);
helpers.formatApiResponse(200, res, {
uid: uid,
Expand Down

0 comments on commit 7b6d43b

Please sign in to comment.