Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save LimarenkoDenis/cfd24bb97b5790fb2982cf76a6d7ee7a to your computer and use it in GitHub Desktop.
Save LimarenkoDenis/cfd24bb97b5790fb2982cf76a6d7ee7a to your computer and use it in GitHub Desktop.
const express = require('express');
const router = express.Router();
const models = require('../models');
router.param('id', (req, res, next) => {
req.findOne = models.customer.findOne({
where: {
id: req.params.id
}
});
next();
});
router
.get('/customers', (req, res, next) => {
models.customer.findAll()
.then(res.json.bind(res))
.catch(next);
})
.get('/customers/:id', (req, res, next) => {
req.findOne
.then(customer => {
if (!customer) {
return next();
}
return res.json(customer);
})
.catch(next);
})
.post('/customers', (req, res, next) => {
const data = req.body;
models.customer.create(data)
.then(res.json.bind(res))
.catch(next);
})
.put('/customers/:id', (req, res, next) => {
req.findOne
.then(data => {
if (!data) {
return next();
}
const customer = Object.assign(data, req.body);
return customer.save()
.then(() => {
res.json(customer);
});
})
.catch(next);
})
.delete('/customers/:id', (req, res, next) => {
models.customer.destroy({
where: {
id: req.params.id
}
})
.then(deleted => {
if (!deleted) {
return next();
}
return res.end('204');
})
.catch(next);
});
module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment