UNPKG

slush-y

Version:

A slush generator for Best Practices with AngularJS Fullstack applications.

89 lines (80 loc) 2.45 kB
/** * Using Rails-like standard naming convention for endpoints. * GET /articles -> index * POST /articles -> create * GET /articles/:id -> show * PUT /articles/:id -> update * DELETE /articles/:id -> destroy */ 'use strict'; var _ = require('lodash'); var Article = require('./article.model'); // Get list of articles exports.index = function(req, res) { Article.find(function (err, articles) { if(err) { return handleError(res, err); } return res.json(200, articles); }); }; // Get a single article exports.show = function(req, res) { Article.findById(req.params.id, function (err, article) { if(err) { return handleError(res, err); } if(!article) { return res.send(404); } return res.json(article); }); }; // Creates a new article in the DB. exports.create = function(req, res) { Article.create(req.body, function(err, article) { if(err) { return handleError(res, err); } return res.json(201, article); }); }; // Updates an existing article in the DB. exports.update = function(req, res) { if(req.body._id) { delete req.body._id; } Article.findById(req.params.id, function (err, article) { if (err) { return handleError(res, err); } if(!article) { return res.send(404); } var updated = _.merge(article, req.body); updated.save(function (err) { if (err) { return handleError(res, err); } return res.json(200, article); }); }); }; // Deletes a article from the DB. exports.destroy = function(req, res) { Article.findById(req.params.id, function (err, article) { if(err) { return handleError(res, err); } if(!article) { return res.send(404); } article.remove(function(err) { if(err) { return handleError(res, err); } return res.send(204); }); }); }; /** * Article middleware */ exports.articleByID = function(req, res, next, id) { Article.findById(id).populate('user', 'displayName').exec(function(err, article) { if (err) return next(err); if (!article) return next(new Error('Failed to load Article ' + id)); req.article = article; next(); }); }; /** * Article authorization middleware */ exports.hasAuthorization = function(req, res, next) { if (req.article.user.id !== req.user.id) { return res.send(403, 'User is not authorized'); } next(); }; function handleError(res, err) { return res.send(500, err); }