Files
meanTorrent/modules/articles/server/controllers/articles.server.controller.js
Michael Leanos 0ea8cec120 fix(express): Incorrest uses of 400 error codes (#1553)
Fixes incorrest usage of 400 HTTP responses being returned from the
server, in favor of using 422.

Also, changed a few return codes to 401 where it was more appropriate.

See this article for reasoning behind moving to 422, and why 400 isn't
appropriate for these cases.

For ref:
6be12f8a06

Related:
https://github.com/meanjs/mean/pull/1547
https://github.com/meanjs/mean/pull/1510
2016-10-10 16:00:24 -07:00

118 lines
2.6 KiB
JavaScript

'use strict';
/**
* Module dependencies
*/
var path = require('path'),
mongoose = require('mongoose'),
Article = mongoose.model('Article'),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));
/**
* Create an article
*/
exports.create = function (req, res) {
var article = new Article(req.body);
article.user = req.user;
article.save(function (err) {
if (err) {
return res.status(422).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(article);
}
});
};
/**
* Show the current article
*/
exports.read = function (req, res) {
// convert mongoose document to JSON
var article = req.article ? req.article.toJSON() : {};
// Add a custom field to the Article, for determining if the current User is the "owner".
// NOTE: This field is NOT persisted to the database, since it doesn't exist in the Article model.
article.isCurrentUserOwner = !!(req.user && article.user && article.user._id.toString() === req.user._id.toString());
res.json(article);
};
/**
* Update an article
*/
exports.update = function (req, res) {
var article = req.article;
article.title = req.body.title;
article.content = req.body.content;
article.save(function (err) {
if (err) {
return res.status(422).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(article);
}
});
};
/**
* Delete an article
*/
exports.delete = function (req, res) {
var article = req.article;
article.remove(function (err) {
if (err) {
return res.status(422).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(article);
}
});
};
/**
* List of Articles
*/
exports.list = function (req, res) {
Article.find().sort('-created').populate('user', 'displayName').exec(function (err, articles) {
if (err) {
return res.status(422).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(articles);
}
});
};
/**
* Article middleware
*/
exports.articleByID = function (req, res, next, id) {
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).send({
message: 'Article is invalid'
});
}
Article.findById(id).populate('user', 'displayName').exec(function (err, article) {
if (err) {
return next(err);
} else if (!article) {
return res.status(404).send({
message: 'No article with that identifier has been found'
});
}
req.article = article;
next();
});
};