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