TwoToc code
[YouAndWeb_TwoToc] / server / api / message / message.controller.js
1 /**
2  * Using Rails-like standard naming convention for endpoints.
3  * GET     /api/test              ->  index
4  * POST    /api/test              ->  create
5  * GET     /api/test/:id          ->  show
6  * PUT     /api/test/:id          ->  update
7  * DELETE  /api/test/:id          ->  destroy
8  */
9
10 'use strict';
11
12 var _ = require('lodash');
13 var Message = require('./message.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 Messages
63 exports.index = function(req, res) {
64   Message.findAsync()
65     .then(responseWithResult(res))
66     .catch(handleError(res));
67 };
68
69 // Gets a single Message from the DB
70 exports.show = function(req, res) {
71   Message.findByIdAsync(req.params.id)
72     .then(handleEntityNotFound(res))
73     .then(responseWithResult(res))
74     .catch(handleError(res));
75 };
76
77 // Creates a new Message in the DB
78 exports.create = function(req, res) {
79   Message.createAsync(req.body)
80     .then(responseWithResult(res, 201))
81     .catch(handleError(res));
82 };
83
84 // Updates an existing Message in the DB
85 exports.update = function(req, res) {
86   if (req.body._id) {
87     delete req.body._id;
88   }
89   Message.findByIdAsync(req.params.id)
90     .then(handleEntityNotFound(res))
91     .then(saveUpdates(req.body))
92     .then(responseWithResult(res))
93     .catch(handleError(res));
94 };
95
96 // Deletes a Message from the DB
97 exports.destroy = function(req, res) {
98   Message.findByIdAsync(req.params.id)
99     .then(handleEntityNotFound(res))
100     .then(removeEntity(res))
101     .catch(handleError(res));
102 };