forked from skasch/voting-app
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththing.controller.js
More file actions
68 lines (60 loc) · 1.91 KB
/
thing.controller.js
File metadata and controls
68 lines (60 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* Using Rails-like standard naming convention for endpoints.
* GET /things -> index
* POST /things -> create
* GET /things/:id -> show
* PUT /things/:id -> update
* DELETE /things/:id -> destroy
*/
'use strict';
var _ = require('lodash');
var Thing = require('./thing.model');
// Get list of things
exports.index = function(req, res) {
Thing.find(function (err, things) {
if(err) { return handleError(res, err); }
return res.status(200).json(things);
});
};
// Get a single thing
exports.show = function(req, res) {
Thing.findById(req.params.id, function (err, thing) {
if(err) { return handleError(res, err); }
if(!thing) { return res.status(404).send('Not Found'); }
return res.json(thing);
});
};
// Creates a new thing in the DB.
exports.create = function(req, res) {
Thing.create(req.body, function(err, thing) {
if(err) { return handleError(res, err); }
return res.status(201).json(thing);
});
};
// Updates an existing thing in the DB.
exports.update = function(req, res) {
if(req.body._id) { delete req.body._id; }
Thing.findById(req.params.id, function (err, thing) {
if (err) { return handleError(res, err); }
if(!thing) { return res.status(404).send('Not Found'); }
var updated = _.merge(thing, req.body);
updated.save(function (err) {
if (err) { return handleError(res, err); }
return res.status(200).json(thing);
});
});
};
// Deletes a thing from the DB.
exports.destroy = function(req, res) {
Thing.findById(req.params.id, function (err, thing) {
if(err) { return handleError(res, err); }
if(!thing) { return res.status(404).send('Not Found'); }
thing.remove(function(err) {
if(err) { return handleError(res, err); }
return res.status(204).send('No Content');
});
});
};
function handleError(res, err) {
return res.status(500).send(err);
}