6b39f83cd50af0ec16996cdfeedf0c1c20c8dba8
[motion.git] / server / api / desk_field / desk_field.controller.js
1 /**
2  * Using Rails-like standard naming convention for endpoints.
3  * GET     /api/desk/fields              ->  index
4  * POST    /api/desk/fields              ->  create
5  * GET     /api/desk/fields/:id          ->  show
6  * PUT     /api/desk/fields/:id          ->  update
7  * DELETE  /api/desk/fields/:id          ->  destroy
8  */
9
10 'use strict';
11
12
13 var _ = require('lodash');
14
15 var DeskField = require('../../models').DeskField;
16
17
18 function handleError(res, statusCode) {
19   statusCode = statusCode || 500;
20   return function(err) {
21     res.status(statusCode).send(err);
22   };
23 }
24
25 function responseWithResult(res, statusCode) {
26   statusCode = statusCode || 200;
27   return function(entity) {
28     if (entity) {
29       res.status(statusCode).json(entity);
30     }
31   };
32 }
33
34 function handleEntityNotFound(res) {
35   return function(entity) {
36     if (!entity) {
37       res.status(404).end();
38       return null;
39     }
40     return entity;
41   };
42 }
43
44 function saveUpdates(updates) {
45   return function(entity) {
46     return entity.updateAttributes(updates)
47       .then(function(updated) {
48         return updated;
49       });
50   };
51 }
52
53 function removeEntity(res) {
54   return function(entity) {
55     if (entity) {
56       return entity.destroy()
57         .then(function() {
58           res.status(204).end();
59         });
60     }
61   };
62 }
63
64 // Gets a list of DeskFields
65 exports.index = function(req, res) {
66   DeskField.findAll()
67     .then(responseWithResult(res))
68     .catch(handleError(res));
69 }
70
71 // Gets a single DeskField from the DB
72 exports.show = function(req, res) {
73   DeskField.findById(req.params.id)
74     .then(handleEntityNotFound(res))
75     .then(responseWithResult(res))
76     .catch(handleError(res));
77 }
78
79 // Creates a new DeskField in the DB
80 exports.create = function(req, res) {
81   DeskField.create(req.body)
82     .then(responseWithResult(res, 201))
83     .catch(handleError(res));
84 }
85
86 // Updates an existing DeskField in the DB
87 exports.update = function(req, res) {
88   if (req.body.id) {
89     delete req.body.id;
90   }
91   DeskField.findById(req.params.id)
92     .then(handleEntityNotFound(res))
93     .then(saveUpdates(req.body))
94     .then(responseWithResult(res))
95     .catch(handleError(res));
96 }
97
98 // Deletes a DeskField from the DB
99 exports.destroy = function(req, res) {
100   DeskField.findById(req.params.id)
101     .then(handleEntityNotFound(res))
102     .then(removeEntity(res))
103     .catch(handleError(res));
104 }