note.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. var models = require('../models');
  2. var Note = models.Note;
  3. var User = models.User;
  4. var Category = models.Category;
  5. var noteSafeParams = ["id", "link","description","title","icon","content", "userId", 'CategoryId'];
  6. var userSafeParams = ['id', 'name', 'username', 'bio', 'twitter_handle', 'site'];
  7. module.exports = function(app) {
  8. app.get('/notes', function(req, res) {
  9. models.sequelize.sync().on('success', function() {
  10. Note.findAll({attributes: noteSafeParams, include: [Category, {model: User, attributes: userSafeParams}]}).success(function(notes) {
  11. res.json(notes);
  12. })
  13. });
  14. });
  15. app.post('/notes', function(req, res) {
  16. models.sequelize.sync().on('success', function() {
  17. Note.create({UserId: req.user.id, CategoryId: req.param('CategoryId'), link: req.param('link'), title: req.param('title'), content: req.param('content'), description: req.param('description'), icon: req.param('icon')}).success(function(notes) {
  18. res.json(notes);
  19. })
  20. });
  21. });
  22. app.put('/notes', function(req, res) {
  23. var param;
  24. var updateParams = {};
  25. var noteId = parseInt(req.param('id'));
  26. models.sequelize.sync().on('success', function() {
  27. Note.find({where: {id: noteId}, attributes: noteSafeParams, include: [Category]}).success(function(note) {
  28. // Return an 401 aunauthorized if a user tries to editor another user's note
  29. if(!req.user || req.user.id !== note.values.UserId) {
  30. res.status(401);
  31. res.json({error: "You are not authorized to edit this note"});
  32. return;
  33. }
  34. // Loop through the noteSafeParams and update their values from the given ones.
  35. for(var i=0, l = noteSafeParams.length; i < l; i++ ) {
  36. param = noteSafeParams[i];
  37. updateParams[param] = req.param(param);
  38. }
  39. note.updateAttributes(updateParams).success(function() {
  40. res.json(note);
  41. });
  42. });
  43. });
  44. });
  45. app.get('/notes/:id', function(req, res) {
  46. var noteId = parseInt(req.params.id, 10);
  47. // If a note is not found at the given id, return an empty object
  48. if(!noteId) {
  49. res.json({});
  50. return;
  51. }
  52. models.sequelize.sync().on('success', function() {
  53. Note.find({where: {id: noteId}, attributes: noteSafeParams, include: [Category, {model: User, attributes: userSafeParams}]}).success(function(note) {
  54. res.json(note);
  55. });
  56. });
  57. });
  58. };