-
-
Save bbraithwaite/3a12662755e44b344c3c to your computer and use it in GitHub Desktop.
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
'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(); | |
}); | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A suggestion for cleaning up and reducing boilerplate duplication: https://gist.github.com/kirayatail/b745f05a7b346b6c4f4d