2 * Using Rails-like standard naming convention for endpoints.
3 * GET /api/categories -> index
4 * POST /api/categories -> create
5 * GET /api/categories/:id -> show
6 * PUT /api/categories/:id -> update
7 * DELETE /api/categories/:id -> destroy
12 var _ = require('lodash');
13 var Category = require('./category.model');
15 function handleError(res, statusCode) {
16 statusCode = statusCode || 500;
17 return function(err) {
18 res.status(statusCode).send(err);
22 function responseWithResult(res, statusCode) {
23 statusCode = statusCode || 200;
24 return function(entity) {
26 res.status(statusCode).json(entity);
31 function handleEntityNotFound(res) {
32 return function(entity) {
34 res.status(404).end();
41 function saveUpdates(updates) {
42 return function(entity) {
43 var updated = _.merge(entity, updates);
44 return updated.saveAsync()
45 .spread(function(updated) {
51 function removeEntity(res) {
52 return function(entity) {
54 return entity.removeAsync()
56 res.status(204).end();
62 // Gets a list of Categorys
63 exports.index = function(req, res) {
64 var active = req.query.active;
66 if (active != undefined) {
69 Category.findAsync(sq)
70 .then(responseWithResult(res))
71 .catch(handleError(res));
74 // Gets a single Category from the DB
75 exports.show = function(req, res) {
76 Category.findByIdAsync(req.params.id)
77 .then(handleEntityNotFound(res))
78 .then(responseWithResult(res))
79 .catch(handleError(res));
82 // Creates a new Category in the DB
83 exports.create = function(req, res) {
84 Category.createAsync(req.body)
85 .then(responseWithResult(res, 201))
86 .catch(handleError(res));
89 // Updates an existing Category in the DB
90 exports.update = function(req, res) {
94 Category.findByIdAsync(req.params.id)
95 .then(handleEntityNotFound(res))
96 .then(saveUpdates(req.body))
97 .then(responseWithResult(res))
98 .catch(handleError(res));
101 // Deletes a Category from the DB
102 exports.destroy = function(req, res) {
103 Category.findByIdAsync(req.params.id)
104 .then(handleEntityNotFound(res))
105 .then(removeEntity(res))
106 .catch(handleError(res));