Created
January 24, 2020 21:46
-
-
Save eezhal92/d7763ef939dbb93a4572689a44d384c4 to your computer and use it in GitHub Desktop.
express middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const bodyParser = require('body-parser'); | |
const Validator = require('validatorjs'); | |
const app = express(); | |
// Middleware | |
const memberInputValidationGuard = function (req, res, next) { | |
const data = { | |
name: req.body.name, | |
email: req.body.email, | |
}; | |
const rules = { | |
name: 'required|min:3', | |
email: 'required|email', | |
}; | |
const validation = new Validator(data, rules); | |
if (validation.fails()) { | |
return res.status(422).json({ | |
errors: { | |
name: validation.errors.first('name'), | |
email: validation.errors.first('email'), | |
}, | |
}); | |
} | |
// if validation pass, store data in request object | |
req.data = data; | |
return next(); | |
}; | |
app.use(bodyParser.json()); | |
const members = []; | |
app.get('/members', function (req, res) { | |
res.status(200).json({ members }); | |
}); | |
app.post( | |
'/members', | |
// use middleware | |
// see: https://expressjs.com/en/guide/writing-middleware.html | |
// see: https://expressjs.com/en/guide/using-middleware.html | |
memberInputValidationGuard, | |
function (req, res) { | |
// access data from req object | |
// attached from previous middleware | |
const data = req.data; | |
members.push(data); | |
res.status(201).json({ | |
message: 'User has been created', | |
}); | |
} | |
); | |
const port = 8080; | |
app.listen(port, () => console.log('listening on port', port); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ka kode yg ini utk perbarui request ka? klo dalam case challenge yg ini, tdk apa dihapus kan ka?