revision.js 2.0 KB

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