Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Category = mongoose.model('Category'),
_ = require('lodash');
/**
* Create a Category
*/
exports.create = function(req, res) {
var category = new Category(req.body);
category.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.status(201).json(category);
}
});
};
/**
* Show the current Category
*/
exports.read = function(req, res) {
res.json(req.category);
};
/**
* Update a Category
*/
exports.update = function(req, res) {
var category = req.category;
category = _.extend(category, req.body);
category.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(category);
}
});
};
/**
* Delete an Category
*/
exports.delete = function(req, res) {
var category = req.category;
category.remove(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(category);
}
});
};
/**
* List of Categories
*/
exports.list = function(req, res) {
Category.find().sort('name').exec(function(err, categories) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(categories);
}
});
};
/**
* Category middleware
*/
exports.categoryByID = function(req, res, next, id) {
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).send({
message: 'Category is invalid'
});
}
Category.findById(id).exec(function(err, category) {
if (err) return next(err);
if (!category) {
return res.status(404).send({
message: 'Category not found'
});
}
req.category = category;
next();
});
};
@kirayatail

This comment has been minimized.

Copy link

kirayatail commented Sep 11, 2015

A suggestion for cleaning up and reducing boilerplate duplication: https://gist.github.com/kirayatail/b745f05a7b346b6c4f4d

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.