posts.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /**
  2. * @file
  3. *
  4. *
  5. * User: marand
  6. * Date: 30/08/15
  7. * Time: 10:48
  8. */
  9. // Not a "var", to make it global.
  10. Posts = new Mongo.Collection('posts');
  11. // Removed Posts.allow : we no longer trigger inserts from client.
  12. Posts.allow({
  13. update: function (userId, post) {
  14. return ownsDocument(userId, post);
  15. },
  16. remove: function (userId, post) {
  17. return ownsDocument(userId, post);
  18. }
  19. });
  20. Posts.deny({
  21. update: function (userId, post, fieldNames) {
  22. // _.without() is like PHP array_diff($source, ...$keys).
  23. return (_.without(fieldNames, "url", "title").length > 0);
  24. }
  25. });
  26. Posts.deny({
  27. // In a post edit, the update is performed by a $set modifier, with the same
  28. // fields as the base inserted post: url and title, so we can pass it to
  29. // the post validator as it currently stands.
  30. update: function (userId, post, fieldNames, modifier) {
  31. var errors = validatePost(modifier.$set);
  32. return errors.title || errors.url;
  33. }
  34. });
  35. // This is in lib/ instead of server/ for latency compensation.
  36. Meteor.methods({
  37. postInsert: function(postAttributes) {
  38. "use strict";
  39. check(Meteor.userId(), String);
  40. check(postAttributes, {
  41. title: String,
  42. url: String
  43. });
  44. var errors = validatePost(postAttributes);
  45. if (errors.title || errors.url) {
  46. throw new Meteor.Error('invalid-post',
  47. "You must set a title and URL for your post");
  48. }
  49. var postWithSameLink = Posts.findOne({ url: postAttributes.url });
  50. if (postWithSameLink) {
  51. // Return to skip the insert.
  52. return {
  53. postExists: true,
  54. _id: postWithSameLink._id
  55. };
  56. }
  57. var user = Meteor.user();
  58. var post = _.extend(postAttributes, {
  59. userId: user._id,
  60. author: user.username,
  61. submitted: new Date()
  62. });
  63. var postId = Posts.insert(post);
  64. return {
  65. _id: postId
  66. };
  67. }
  68. });
  69. validatePost = function (post) {
  70. var errors = {};
  71. if (!post.title) {
  72. errors.title = "Please fill in a headline";
  73. }
  74. if (!post.url) {
  75. errors.url = "Please fill in a URL";
  76. }
  77. return errors;
  78. };