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
12 var _ = require('lodash');
13 var Message = require('./message.model');
15 function handleError(res, statusCode) {
16 statusCode = statusCode || 500;
17 return function(err) {
18 res.status(statusCode).send(err);
22 function responseWithResult(res, statusCode) {
23 statusCode = statusCode || 200;
24 return function(entity) {
26 res.status(statusCode).json(entity);
31 function handleEntityNotFound(res) {
32 return function(entity) {
34 res.status(404).end();
41 function saveUpdates(updates) {
42 return function(entity) {
43 var updated = _.merge(entity, updates);
44 return updated.saveAsync()
45 .spread(function(updated) {
51 function removeEntity(res) {
52 return function(entity) {
54 return entity.removeAsync()
56 res.status(204).end();
62 // Gets a list of Messages
63 exports.index = function(req, res) {
65 .then(responseWithResult(res))
66 .catch(handleError(res));
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));
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));
84 // Updates an existing Message in the DB
85 exports.update = function(req, res) {
89 Message.findByIdAsync(req.params.id)
90 .then(handleEntityNotFound(res))
91 .then(saveUpdates(req.body))
92 .then(responseWithResult(res))
93 .catch(handleError(res));
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));