Skip to content

Instantly share code, notes, and snippets.

@ayushgp
Created April 14, 2016 04:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayushgp/a5739a805c211b4729d1439a5576cb2d to your computer and use it in GitHub Desktop.
Save ayushgp/a5739a805c211b4729d1439a5576cb2d to your computer and use it in GitHub Desktop.
/**
* Using Rails-like standard naming convention for endpoints.
* GET /api/things -> index
* POST /api/things -> create
* GET /api/things/:id -> show
* PUT /api/things/:id -> update
* DELETE /api/things/:id -> destroy
*/
'use strict';
var _ = require('lodash');
var Thing = require('./thing.model');
function handleError(res, statusCode) {
statusCode = statusCode || 500;
return function(err) {
res.status(statusCode).send(err);
};
}
function responseWithResult(res, statusCode) {
statusCode = statusCode || 200;
return function(entity) {
if (entity) {
res.status(statusCode).json(entity);
}
};
}
function handleEntityNotFound(res) {
return function(entity) {
if (!entity) {
res.status(404).end();
return null;
}
return entity;
};
}
function saveUpdates(updates) {
return function(entity) {
var updated = _.merge(entity, updates);
return updated.saveAsync()
.spread(function(updated) {
return updated;
});
};
}
function removeEntity(res) {
return function(entity) {
if (entity) {
return entity.removeAsync()
.then(function() {
res.status(204).end();
});
}
};
}
// Gets a list of Things
exports.index = function(req, res) {
Thing.findAsync()
.then(responseWithResult(res))
.catch(handleError(res));
};
// Gets a single Thing from the DB
exports.show = function(req, res) {
Thing.findByIdAsync(req.params.id)
.then(handleEntityNotFound(res))
.then(responseWithResult(res))
.catch(handleError(res));
};
// Creates a new Thing in the DB
exports.create = function(req, res) {
Thing.createAsync(req.body)
.then(responseWithResult(res, 201))
.catch(handleError(res));
};
// Updates an existing Thing in the DB
exports.update = function(req, res) {
if (req.body._id) {
delete req.body._id;
}
Thing.findByIdAsync(req.params.id)
.then(handleEntityNotFound(res))
.then(saveUpdates(req.body))
.then(responseWithResult(res))
.catch(handleError(res));
};
// Deletes a Thing from the DB
exports.destroy = function(req, res) {
Thing.findByIdAsync(req.params.id)
.then(handleEntityNotFound(res))
.then(removeEntity(res))
.catch(handleError(res));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment