news.js 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. var ip = require('ip');
  2. var NewsItem = require('../models/NewsItem');
  3. var logger = require('../utils/logger');
  4. var validation = require('../validation');
  5. /* CREATE (GUARDED) */
  6. /**
  7. * Function for creating a new news item in the DB.
  8. * @param req The request object sent over from the route.
  9. * @param res The response object sent over from the route.
  10. */
  11. exports.createNewsItem = function (req, res) {
  12. //Get the title and contents from the request body
  13. var title = req.body.title;
  14. var contents = req.body.contents;
  15. //Check that valid params were supplied
  16. var valid = validation.validateNewsItem(res, {title: title, contents: contents});
  17. //If so, continue
  18. if (valid) {
  19. //Make a new NewsItem object with the given info
  20. var newNews = new NewsItem({
  21. title: title,
  22. contents: contents
  23. });
  24. //Save the new news item in the DB
  25. newNews.save(function (err) {
  26. //If there was an error while saving
  27. if (err) {
  28. logger.info("[" + ip.address() + "] New news item creation failed.");
  29. res.status(422).send({created: false, errors: err});
  30. }
  31. //Otherwise, new item was added successfully
  32. else {
  33. logger.info("[" + ip.address() + "] New news item creation succeeded.");
  34. res.status(201).send({created: true});
  35. }
  36. });
  37. }
  38. //Else condition is handled in validation
  39. };
  40. /* READ (UNGUARDED) */
  41. /**
  42. * Function for getting all news items from the DB.
  43. * @param req The request object sent over from the route.
  44. * @param res The response object sent over from the route.
  45. */
  46. exports.getAll = function (req, res) {
  47. //Find all news item, but only return the title, contents and date.
  48. NewsItem.find({}, {_id: false, title: true, contents: true, date: true}, function (err, news) {
  49. //If there was an error during the find, send back an error.
  50. if (err)
  51. res.status(404).send({message: "Could not retrieve News.", errors: err});
  52. //Otherwise, send back the items.
  53. else
  54. res.status(200).send(news);
  55. });
  56. };
  57. /* UPDATE (GUARDED) */
  58. /* DELETE (GUARDED) */