revision.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. const ObjectId = mongoose.Schema.Types.ObjectId;
  10. const revisionSchema = new mongoose.Schema({
  11. // OBSOLETE path: { type: String, required: true, index: true }
  12. pageId: { type: ObjectId, required: true, index: true },
  13. body: {
  14. type: String,
  15. required: true,
  16. get: (data) => {
  17. // replace CR/CRLF to LF above v3.1.5
  18. // see https://github.com/weseek/growi/issues/463
  19. return data ? data.replace(/\r\n?/g, '\n') : '';
  20. },
  21. },
  22. format: { type: String, default: 'markdown' },
  23. author: { type: ObjectId, ref: 'User' },
  24. createdAt: { type: Date, default: Date.now },
  25. hasDiffToPrev: { type: Boolean },
  26. });
  27. revisionSchema.plugin(mongoosePaginate);
  28. revisionSchema.statics.findRevisionIdList = function(path) {
  29. return this.find({ path })
  30. .select('_id author createdAt hasDiffToPrev')
  31. .sort({ createdAt: -1 })
  32. .exec();
  33. };
  34. revisionSchema.statics.updateRevisionListByPath = async function(path, updateData) {
  35. const Revision = this;
  36. return Revision.updateMany({ path }, { $set: updateData });
  37. };
  38. revisionSchema.statics.prepareRevision = function(pageData, body, previousBody, user, options) {
  39. const Revision = this;
  40. if (!options) {
  41. // eslint-disable-next-line no-param-reassign
  42. options = {};
  43. }
  44. const format = options.format || 'markdown';
  45. if (!user._id) {
  46. throw new Error('Error: user should have _id');
  47. }
  48. const newRevision = new Revision();
  49. newRevision.pageId = pageData._id;
  50. newRevision.body = body;
  51. newRevision.format = format;
  52. newRevision.author = user._id;
  53. newRevision.createdAt = Date.now();
  54. if (pageData.revision != null) {
  55. newRevision.hasDiffToPrev = body !== previousBody;
  56. }
  57. return newRevision;
  58. };
  59. return mongoose.model('Revision', revisionSchema);
  60. };