page.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. /* eslint-disable @typescript-eslint/no-explicit-any */
  2. import mongoose, {
  3. Schema, Model, Document,
  4. } from 'mongoose';
  5. import mongoosePaginate from 'mongoose-paginate-v2';
  6. import uniqueValidator from 'mongoose-unique-validator';
  7. import nodePath from 'path';
  8. import { getOrCreateModel } from '@growi/core';
  9. import loggerFactory from '../../utils/logger';
  10. import Crowi from '../crowi';
  11. import { IPage } from './interfaces/page';
  12. import { getPageSchema, PageQueryBuilder } from './obsolete-page';
  13. const logger = loggerFactory('growi:models:page');
  14. /*
  15. * define schema
  16. */
  17. const GRANT_PUBLIC = 1;
  18. const GRANT_RESTRICTED = 2;
  19. const GRANT_SPECIFIED = 3;
  20. const GRANT_OWNER = 4;
  21. const GRANT_USER_GROUP = 5;
  22. const PAGE_GRANT_ERROR = 1;
  23. const STATUS_PUBLISHED = 'published';
  24. const STATUS_DELETED = 'deleted';
  25. export interface PageDocument extends IPage, Document {}
  26. export interface PageModel extends Model<PageDocument> {
  27. createEmptyPagesByPaths(paths: string[]): Promise<void>
  28. getParentIdAndFillAncestors(path: string): Promise<string | null>
  29. }
  30. const ObjectId = mongoose.Schema.Types.ObjectId;
  31. const schema = new Schema<PageDocument, PageModel>({
  32. parent: {
  33. type: ObjectId, ref: 'Page', index: true, default: null,
  34. },
  35. isEmpty: { type: Boolean, default: false },
  36. path: {
  37. type: String, required: true, index: true,
  38. },
  39. revision: { type: ObjectId, ref: 'Revision' },
  40. redirectTo: { type: String, index: true },
  41. status: { type: String, default: STATUS_PUBLISHED, index: true },
  42. grant: { type: Number, default: GRANT_PUBLIC, index: true },
  43. grantedUsers: [{ type: ObjectId, ref: 'User' }],
  44. grantedGroup: { type: ObjectId, ref: 'UserGroup', index: true },
  45. creator: { type: ObjectId, ref: 'User', index: true },
  46. lastUpdateUser: { type: ObjectId, ref: 'User' },
  47. liker: [{ type: ObjectId, ref: 'User' }],
  48. seenUsers: [{ type: ObjectId, ref: 'User' }],
  49. commentCount: { type: Number, default: 0 },
  50. slackChannels: { type: String },
  51. pageIdOnHackmd: { type: String },
  52. revisionHackmdSynced: { type: ObjectId, ref: 'Revision' }, // the revision that is synced to HackMD
  53. hasDraftOnHackmd: { type: Boolean }, // set true if revision and revisionHackmdSynced are same but HackMD document has modified
  54. createdAt: { type: Date, default: Date.now },
  55. updatedAt: { type: Date, default: Date.now },
  56. deleteUser: { type: ObjectId, ref: 'User' },
  57. deletedAt: { type: Date },
  58. }, {
  59. toJSON: { getters: true },
  60. toObject: { getters: true },
  61. });
  62. // apply plugins
  63. schema.plugin(mongoosePaginate);
  64. schema.plugin(uniqueValidator);
  65. /*
  66. * Methods
  67. */
  68. const collectAncestorPaths = (path: string, ancestorPaths: string[] = []): string[] => {
  69. const parentPath = nodePath.dirname(path);
  70. ancestorPaths.push(parentPath);
  71. if (path !== '/') return collectAncestorPaths(parentPath, ancestorPaths);
  72. return ancestorPaths;
  73. };
  74. schema.statics.createEmptyPagesByPaths = async function(paths: string[]): Promise<void> {
  75. // find existing parents
  76. const builder = new PageQueryBuilder(this.find({}, { _id: 0, path: 1 }));
  77. const existingPages = await builder
  78. .addConditionToListByPathsArray(paths)
  79. .query
  80. .lean()
  81. .exec();
  82. const existingPagePaths = existingPages.map(page => page.path);
  83. // paths to create empty pages
  84. const notExistingPagePaths = paths.filter(path => !existingPagePaths.includes(path));
  85. // insertMany empty pages
  86. try {
  87. await this.insertMany(notExistingPagePaths.map(path => ({ path, isEmpty: true })));
  88. }
  89. catch (err) {
  90. logger.error('Failed to insert empty pages.', err);
  91. throw err;
  92. }
  93. };
  94. schema.statics.getParentIdAndFillAncestors = async function(path: string): Promise<string | null> {
  95. const parentPath = nodePath.dirname(path);
  96. const parent = await this.findOne({ path: parentPath }); // find the oldest parent which must always be the true parent
  97. if (parent != null) { // fill parents if parent is null
  98. return parent._id;
  99. }
  100. const ancestorPaths = collectAncestorPaths(path); // paths of parents need to be created
  101. // just create ancestors with empty pages
  102. await this.createEmptyPagesByPaths(ancestorPaths);
  103. // find ancestors
  104. const builder = new PageQueryBuilder(this.find({}, { _id: 1, path: 1 }));
  105. const ancestors = await builder
  106. .addConditionToListByPathsArray(ancestorPaths)
  107. .query
  108. .lean()
  109. .exec();
  110. const ancestorsMap = new Map(); // Map<path, _id>
  111. ancestors.forEach(page => ancestorsMap.set(page.path, page._id));
  112. // bulkWrite to update ancestors
  113. const nonRootAncestors = ancestors.filter(page => page.path !== '/');
  114. const operations = nonRootAncestors.map((page) => {
  115. const { path } = page;
  116. const parentPath = nodePath.dirname(path);
  117. return {
  118. updateOne: {
  119. filter: {
  120. path,
  121. },
  122. update: {
  123. parent: ancestorsMap.get(parentPath),
  124. },
  125. },
  126. };
  127. });
  128. await this.bulkWrite(operations);
  129. const parentId = ancestorsMap.get(parentPath);
  130. return parentId;
  131. };
  132. export default (crowi: Crowi): any => {
  133. // add old page schema methods
  134. const pageSchema = getPageSchema(crowi);
  135. schema.methods = { ...pageSchema.methods, ...schema.methods };
  136. schema.statics = { ...pageSchema.statics, ...schema.statics };
  137. return getOrCreateModel<PageDocument, PageModel>('Page', schema);
  138. };