posts.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. // This is in lib/ instead of server/ for latency compensation.
  27. Meteor.methods({
  28. postInsert: function(postAttributes) {
  29. "use strict";
  30. check(Meteor.userId(), String);
  31. check(postAttributes, {
  32. title: String,
  33. url: String
  34. });
  35. var errors = validatePost(postAttributes);
  36. if (errors.title || errors.url) {
  37. throw new Meteor.Error('invalid-post',
  38. "You must set a title and URL for your post");
  39. }
  40. var postWithSameLink = Posts.findOne({ url: postAttributes.url });
  41. if (postWithSameLink) {
  42. // Return to skip the insert.
  43. return {
  44. postExists: true,
  45. _id: postWithSameLink._id
  46. };
  47. }
  48. var user = Meteor.user();
  49. var post = _.extend(postAttributes, {
  50. userId: user._id,
  51. author: user.username,
  52. submitted: new Date()
  53. });
  54. var postId = Posts.insert(post);
  55. return {
  56. _id: postId
  57. };
  58. }
  59. });
  60. validatePost = function (post) {
  61. var errors = {};
  62. if (!post.title) {
  63. errors.title = "Please fill in a headline";
  64. }
  65. if (!post.url) {
  66. errors.url = "Please fill in a URL";
  67. }
  68. return errors;
  69. };