Skip to content

Instantly share code, notes, and snippets.

@eezhal92
Created January 24, 2020 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eezhal92/d7763ef939dbb93a4572689a44d384c4 to your computer and use it in GitHub Desktop.
Save eezhal92/d7763ef939dbb93a4572689a44d384c4 to your computer and use it in GitHub Desktop.
express middleware
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);
@zulnabil
Copy link

req.data = data;

ka kode yg ini utk perbarui request ka? klo dalam case challenge yg ini, tdk apa dihapus kan ka?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment