revision.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { allOrigin } from '@growi/core';
  2. import loggerFactory from '~/utils/logger';
  3. // disable no-return-await for model functions
  4. /* eslint-disable no-return-await */
  5. module.exports = function(crowi) {
  6. // eslint-disable-next-line no-unused-vars
  7. const logger = loggerFactory('growi:models:revision');
  8. const mongoose = require('mongoose');
  9. const mongoosePaginate = require('mongoose-paginate-v2');
  10. // allow empty strings
  11. mongoose.Schema.Types.String.checkRequired(v => v != null);
  12. const ObjectId = mongoose.Schema.Types.ObjectId;
  13. const revisionSchema = new mongoose.Schema({
  14. // OBSOLETE path: { type: String, required: true, index: true }
  15. pageId: { type: ObjectId, required: true, index: true },
  16. body: {
  17. type: String,
  18. required: true,
  19. get: (data) => {
  20. // replace CR/CRLF to LF above v3.1.5
  21. // see https://github.com/weseek/growi/issues/463
  22. return data ? data.replace(/\r\n?/g, '\n') : '';
  23. },
  24. },
  25. format: { type: String, default: 'markdown' },
  26. author: { type: ObjectId, ref: 'User' },
  27. hasDiffToPrev: { type: Boolean },
  28. origin: { type: String, enum: allOrigin },
  29. }, {
  30. timestamps: { createdAt: true, updatedAt: false },
  31. });
  32. revisionSchema.plugin(mongoosePaginate);
  33. revisionSchema.statics.updateRevisionListByPageId = async function(pageId, updateData) {
  34. return this.updateMany({ pageId }, { $set: updateData });
  35. };
  36. revisionSchema.statics.prepareRevision = function(pageData, body, previousBody, user, origin, options) {
  37. const Revision = this;
  38. if (!options) {
  39. // eslint-disable-next-line no-param-reassign
  40. options = {};
  41. }
  42. const format = options.format || 'markdown';
  43. if (!user._id) {
  44. throw new Error('Error: user should have _id');
  45. }
  46. const newRevision = new Revision();
  47. newRevision.pageId = pageData._id;
  48. newRevision.body = body;
  49. newRevision.format = format;
  50. newRevision.author = user._id;
  51. newRevision.origin = origin;
  52. if (pageData.revision != null) {
  53. newRevision.hasDiffToPrev = body !== previousBody;
  54. }
  55. return newRevision;
  56. };
  57. return mongoose.model('Revision', revisionSchema);
  58. };