unsavedEdits.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // This collection shouldn't be manipulated directly by instead throw the
  2. // `UnsavedEdits` API on the client.
  3. UnsavedEditCollection = new Mongo.Collection('unsaved-edits');
  4. UnsavedEditCollection.attachSchema(
  5. new SimpleSchema({
  6. fieldName: {
  7. type: String,
  8. },
  9. docId: {
  10. type: String,
  11. },
  12. value: {
  13. type: String,
  14. },
  15. userId: {
  16. type: String,
  17. // eslint-disable-next-line consistent-return
  18. autoValue() {
  19. if (this.isInsert && !this.isSet) {
  20. return this.userId;
  21. }
  22. },
  23. },
  24. createdAt: {
  25. type: Date,
  26. optional: true,
  27. // eslint-disable-next-line consistent-return
  28. autoValue() {
  29. if (this.isInsert) {
  30. return new Date();
  31. } else {
  32. this.unset();
  33. }
  34. },
  35. },
  36. modifiedAt: {
  37. type: Date,
  38. denyUpdate: false,
  39. // eslint-disable-next-line consistent-return
  40. autoValue() {
  41. if (this.isInsert || this.isUpsert || this.isUpdate) {
  42. return new Date();
  43. } else {
  44. this.unset();
  45. }
  46. },
  47. },
  48. })
  49. );
  50. UnsavedEditCollection.before.update(
  51. (userId, doc, fieldNames, modifier, options) => {
  52. modifier.$set = modifier.$set || {};
  53. modifier.$set.modifiedAt = Date.now();
  54. }
  55. );
  56. if (Meteor.isServer) {
  57. function isAuthor(userId, doc, fieldNames = []) {
  58. return userId === doc.userId && fieldNames.indexOf('userId') === -1;
  59. }
  60. Meteor.startup(() => {
  61. UnsavedEditCollection._collection._ensureIndex({ modifiedAt: -1 });
  62. UnsavedEditCollection._collection._ensureIndex({ userId: 1 });
  63. });
  64. UnsavedEditCollection.allow({
  65. insert: isAuthor,
  66. update: isAuthor,
  67. remove: isAuthor,
  68. fetch: ['userId'],
  69. });
  70. }
  71. export default UnsavedEditCollection;