posts.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. commentsCount: 0
  63. });
  64. var postId = Posts.insert(post);
  65. return {
  66. _id: postId
  67. };
  68. }
  69. });
  70. validatePost = function (post) {
  71. var errors = {};
  72. if (!post.title) {
  73. errors.title = "Please fill in a headline";
  74. }
  75. if (!post.url) {
  76. errors.url = "Please fill in a URL";
  77. }
  78. return errors;
  79. };