2 * Using Rails-like standard naming convention for endpoints.
3 * GET /api/comments -> index
4 * POST /api/comments -> create
5 * GET /api/comments/:id -> show
6 * PUT /api/comments/:id -> update
7 * DELETE /api/comments/:id -> destroy
12 var _ = require('lodash');
13 var Comment = require('./comment.model');
14 var User = require('../user/user.model');
16 function handleError(res, statusCode) {
17 statusCode = statusCode || 500;
18 return function(err) {
19 res.status(statusCode).send(err);
23 function responseWithResult(res, dig, statusCode) {
24 statusCode = statusCode || 200;
26 return function(entity) {
29 entity.forEach(function(obj, index) {
30 promise.push(new Promise(function(resolve, reject) {
31 User.findById(obj.setterId, function(err, userObj) {
37 Promise.all(promise).then(function(data) {
39 res.status(statusCode).json(data);
42 User.findById(entity.userId, function(err, userObj) {
43 entity.user = userObj;
44 res.status(statusCode).json(entity);
51 function handleEntityNotFound(res) {
52 return function(entity) {
54 res.status(404).end();
61 function saveUpdates(updates) {
62 return function(entity) {
63 var updated = _.merge(entity, updates);
64 return updated.saveAsync()
65 .spread(function(updated) {
71 function removeEntity(res) {
72 return function(entity) {
74 return entity.removeAsync()
76 res.status(204).end();
82 // Gets a list of Comments
83 exports.index = function(req, res) {
84 var limit = req.query.limit;
85 var userId = req.query.user;
86 var active = req.query.active;
94 Comment.find(sq).sort( { dateAdded: -1 } ).lean().limit(limit)
95 .then(responseWithResult(res, true))
96 .catch(handleError(res));
99 // Gets a single Comment from the DB
100 exports.show = function(req, res) {
101 Comment.findByIdAsync(req.params.id)
102 .then(handleEntityNotFound(res))
103 .then(responseWithResult(res))
104 .catch(handleError(res));
107 // Creates a new Comment in the DB
108 exports.create = function(req, res) {
109 Comment.createAsync(req.body)
110 .then(responseWithResult(res, 201))
111 .catch(handleError(res));
114 // Updates an existing Comment in the DB
115 exports.update = function(req, res) {
119 Comment.findByIdAsync(req.params.id)
120 .then(handleEntityNotFound(res))
121 .then(saveUpdates(req.body))
122 .then(responseWithResult(res))
123 .catch(handleError(res));
126 // Deletes a Comment from the DB
127 exports.destroy = function(req, res) {
128 Comment.findByIdAsync(req.params.id)
129 .then(handleEntityNotFound(res))
130 .then(removeEntity(res))
131 .catch(handleError(res));