Skip to content

Instantly share code, notes, and snippets.

@codejockie
Created November 3, 2017 22:07
Show Gist options
  • Select an option

  • Save codejockie/ec6e626d36a5ff50b20a4d9ba12e55dd to your computer and use it in GitHub Desktop.

Select an option

Save codejockie/ec6e626d36a5ff50b20a4d9ba12e55dd to your computer and use it in GitHub Desktop.
Category
const Category = require('../category/categoryModel');
class CategoryController {
constructor() { }
static getCategories(req, res) {
Category.find({}, (err, categories) => {
if (err)
return res.status(500);
if (!categories)
return res.status(404).send();
res.send(categories);
});
}
static getCategory(req, res) {
Category.findById(req.param.id, (err, category) => {
if (err)
return res.status(500);
if (!category)
return res.status(404).send();
res.send(category);
});
}
static createCategory(req, res) {
const name = req.body.name;
Category.create(name, (err, category) => {
if (err)
return res.status(400).send();
res.send(category);
});
}
static updateCategory(req, res) {
const name = req.body.name;
Category.findOneAndUpdate({
_id: req.params.id
}, {
set: name
}, {
new: true
}, (err, category) => {
if (err)
return res.status(400).send();
if (!category)
return res.status(404).send();
res.send(category);
});
}
static deleteCategory(req, res) {
Category.findOneAndRemove({
_id: req.params.id
}, (err, category) => {
if (err)
return res.status(400).send();
if (!category)
return res.status(404).send();
res.send(category);
});
}
}
module.exports = CategoryController;
const CategoryController = require('../controllers/Category');
const routes = (router) => {
// Category routes
router
.route('/categories')
.get(CategoryController.getCategories)
.post(CategoryController.createCategory);
router
.route('/categories/:id')
.get(CategoryController.getCategory)
.put(CategoryController.updateCategory)
.delete(CategoryController.deleteCategory);
};
module.exports = routes;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment