TwoToc code
[YouAndWeb_TwoToc] / server / api / category / category.controller.js
1 /**
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
8  */
9
10 'use strict';
11
12 var _ = require('lodash');
13 var Category = require('./category.model');
14
15 function handleError(res, statusCode) {
16   statusCode = statusCode || 500;
17   return function(err) {
18     res.status(statusCode).send(err);
19   };
20 }
21
22 function responseWithResult(res, statusCode) {
23   statusCode = statusCode || 200;
24   return function(entity) {
25     if (entity) {
26       res.status(statusCode).json(entity);
27     }
28   };
29 }
30
31 function handleEntityNotFound(res) {
32   return function(entity) {
33     if (!entity) {
34       res.status(404).end();
35       return null;
36     }
37     return entity;
38   };
39 }
40
41 function saveUpdates(updates) {
42   return function(entity) {
43     var updated = _.merge(entity, updates);
44     return updated.saveAsync()
45       .spread(function(updated) {
46         return updated;
47       });
48   };
49 }
50
51 function removeEntity(res) {
52   return function(entity) {
53     if (entity) {
54       return entity.removeAsync()
55         .then(function() {
56           res.status(204).end();
57         });
58     }
59   };
60 }
61
62 // Gets a list of Categorys
63 exports.index = function(req, res) {
64   var active = req.query.active;
65   var sq = {};
66   if (active != undefined) {
67     sq.active = active;
68   }
69   Category.findAsync(sq)
70     .then(responseWithResult(res))
71     .catch(handleError(res));
72 };
73
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));
80 };
81
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));
87 };
88
89 // Updates an existing Category in the DB
90 exports.update = function(req, res) {
91   if (req.body._id) {
92     delete req.body._id;
93   }
94   Category.findByIdAsync(req.params.id)
95     .then(handleEntityNotFound(res))
96     .then(saveUpdates(req.body))
97     .then(responseWithResult(res))
98     .catch(handleError(res));
99 };
100
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));
107 };