Jelajahi Sumber

Moved createEmptyPagesByPaths method from the page model to the page service

Taichi Masuyama 3 tahun lalu
induk
melakukan
eb32bb622b

+ 0 - 62
packages/app/src/server/models/page.ts

@@ -54,8 +54,6 @@ type PaginatedPages = {
 export type CreateMethod = (path: string, body: string, user, options: PageCreateOptions) => Promise<PageDocument & { _id: any }>
 export type CreateMethod = (path: string, body: string, user, options: PageCreateOptions) => Promise<PageDocument & { _id: any }>
 export interface PageModel extends Model<PageDocument> {
 export interface PageModel extends Model<PageDocument> {
   [x: string]: any; // for obsolete methods
   [x: string]: any; // for obsolete methods
-  // eslint-disable-next-line max-len
-  createEmptyPagesByPaths(paths: string[], user: any | null, onlyMigratedAsExistingPages?: boolean, onlyGrantedAsExistingPages?: boolean, andFilter?): Promise<void>
   findByIdsAndViewer(pageIds: ObjectIdLike[], user, userGroups?, includeEmpty?: boolean): Promise<PageDocument[]>
   findByIdsAndViewer(pageIds: ObjectIdLike[], user, userGroups?, includeEmpty?: boolean): Promise<PageDocument[]>
   findByPathAndViewer(path: string | null, user, userGroups?, useFindOne?: boolean, includeEmpty?: boolean): Promise<PageDocument | PageDocument[] | null>
   findByPathAndViewer(path: string | null, user, userGroups?, useFindOne?: boolean, includeEmpty?: boolean): Promise<PageDocument | PageDocument[] | null>
   findTargetAndAncestorsByPathOrId(pathOrId: string): Promise<TargetAndAncestorsResult>
   findTargetAndAncestorsByPathOrId(pathOrId: string): Promise<TargetAndAncestorsResult>
@@ -482,66 +480,6 @@ export class PageQueryBuilder {
 
 
 }
 }
 
 
-/**
- * Create empty pages if the page in paths didn't exist
- * @param onlyMigratedAsExistingPages Determine whether to include non-migrated pages as existing pages. If a page exists,
- * an empty page will not be created at that page's path.
- */
-schema.statics.createEmptyPagesByPaths = async function(
-    paths: string[],
-    user: any | null,
-    onlyMigratedAsExistingPages = true,
-    onlyGrantedAsExistingPages = true,
-    andFilter?,
-): Promise<void> {
-  const aggregationPipeline: any[] = [];
-  // 1. Filter by paths
-  aggregationPipeline.push({ $match: { path: { $in: paths } } });
-  // 2. Normalized condition
-  if (onlyMigratedAsExistingPages) {
-    aggregationPipeline.push({
-      $match: {
-        $or: [
-          { grant: GRANT_PUBLIC },
-          { parent: { $ne: null } },
-          { path: '/' },
-        ],
-      },
-    });
-  }
-  // 3. Add custom pipeline
-  if (andFilter != null) {
-    aggregationPipeline.push({ $match: andFilter });
-  }
-  // 4. Add grant conditions
-  let userGroups = null;
-  if (onlyGrantedAsExistingPages) {
-    if (user != null) {
-      const UserGroupRelation = mongoose.model('UserGroupRelation') as any;
-      userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
-    }
-    const grantCondition = this.generateGrantCondition(user, userGroups);
-    aggregationPipeline.push({ $match: grantCondition });
-  }
-
-  // Run aggregation
-  const existingPages = await this.aggregate(aggregationPipeline);
-
-
-  const existingPagePaths = existingPages.map(page => page.path);
-  // paths to create empty pages
-  const notExistingPagePaths = paths.filter(path => !existingPagePaths.includes(path));
-
-  // insertMany empty pages
-  try {
-    await this.insertMany(notExistingPagePaths.map(path => ({ path, isEmpty: true })));
-  }
-  catch (err) {
-    logger.error('Failed to insert empty pages.', err);
-    throw err;
-  }
-};
-
 schema.statics.createEmptyPage = async function(
 schema.statics.createEmptyPage = async function(
     path: string, parent: any, descendantCount = 0, // TODO: improve type including IPage at https://redmine.weseek.co.jp/issues/86506
     path: string, parent: any, descendantCount = 0, // TODO: improve type including IPage at https://redmine.weseek.co.jp/issues/86506
 ): Promise<PageDocument & { _id: any }> {
 ): Promise<PageDocument & { _id: any }> {

+ 66 - 2
packages/app/src/server/service/page.ts

@@ -2821,6 +2821,8 @@ class PageService {
     let nextCount = count;
     let nextCount = count;
     let nextSkiped = skiped;
     let nextSkiped = skiped;
 
 
+    const createEmptyPagesByPaths = this.createEmptyPagesByPaths.bind(this);
+
     const migratePagesStream = new Writable({
     const migratePagesStream = new Writable({
       objectMode: true,
       objectMode: true,
       async write(pages, encoding, callback) {
       async write(pages, encoding, callback) {
@@ -2859,7 +2861,7 @@ class PageService {
           { path: { $nin: publicPathsToNormalize }, status: Page.STATUS_PUBLISHED },
           { path: { $nin: publicPathsToNormalize }, status: Page.STATUS_PUBLISHED },
         ];
         ];
         const filterForApplicableAncestors = { $or: orFilters };
         const filterForApplicableAncestors = { $or: orFilters };
-        await Page.createEmptyPagesByPaths(parentPaths, user, false, true, filterForApplicableAncestors);
+        await createEmptyPagesByPaths(parentPaths, user, false, true, filterForApplicableAncestors);
 
 
         // 3. Find parents
         // 3. Find parents
         const addGrantCondition = (builder) => {
         const addGrantCondition = (builder) => {
@@ -3081,7 +3083,7 @@ class PageService {
 
 
     // just create ancestors with empty pages
     // just create ancestors with empty pages
     const onlyGrantedAsExistingPages = options?.isSystematically;
     const onlyGrantedAsExistingPages = options?.isSystematically;
-    await Page.createEmptyPagesByPaths(ancestorPaths, user, true, onlyGrantedAsExistingPages);
+    await this.createEmptyPagesByPaths(ancestorPaths, user, true, onlyGrantedAsExistingPages);
 
 
     // find ancestors
     // find ancestors
     const builder2 = new PageQueryBuilder(Page.find(), true);
     const builder2 = new PageQueryBuilder(Page.find(), true);
@@ -3123,6 +3125,68 @@ class PageService {
     return createdParent;
     return createdParent;
   }
   }
 
 
+  /**
+   * Create empty pages if the page in paths didn't exist
+   * @param onlyMigratedAsExistingPages Determine whether to include non-migrated pages as existing pages. If a page exists,
+   * an empty page will not be created at that page's path.
+   */
+  async createEmptyPagesByPaths(
+      paths: string[],
+      user: any | null,
+      onlyMigratedAsExistingPages = true,
+      onlyGrantedAsExistingPages = true,
+      andFilter?,
+  ): Promise<void> {
+    const Page = mongoose.model('Page') as unknown as PageModel;
+
+    const aggregationPipeline: any[] = [];
+    // 1. Filter by paths
+    aggregationPipeline.push({ $match: { path: { $in: paths } } });
+    // 2. Normalized condition
+    if (onlyMigratedAsExistingPages) {
+      aggregationPipeline.push({
+        $match: {
+          $or: [
+            { grant: Page.GRANT_PUBLIC },
+            { parent: { $ne: null } },
+            { path: '/' },
+          ],
+        },
+      });
+    }
+    // 3. Add custom pipeline
+    if (andFilter != null) {
+      aggregationPipeline.push({ $match: andFilter });
+    }
+    // 4. Add grant conditions
+    let userGroups = null;
+    if (onlyGrantedAsExistingPages) {
+      if (user != null) {
+        const UserGroupRelation = mongoose.model('UserGroupRelation') as any;
+        userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
+      }
+      const grantCondition = Page.generateGrantCondition(user, userGroups);
+      aggregationPipeline.push({ $match: grantCondition });
+    }
+
+    // Run aggregation
+    const existingPages = await Page.aggregate(aggregationPipeline);
+
+
+    const existingPagePaths = existingPages.map(page => page.path);
+    // paths to create empty pages
+    const notExistingPagePaths = paths.filter(path => !existingPagePaths.includes(path));
+
+    // insertMany empty pages
+    try {
+      await Page.insertMany(notExistingPagePaths.map(path => ({ path, isEmpty: true })));
+    }
+    catch (err) {
+      logger.error('Failed to insert empty pages.', err);
+      throw err;
+    }
+  }
+
 
 
   async create(path: string, body: string, user, options: PageCreateOptions = {}) {
   async create(path: string, body: string, user, options: PageCreateOptions = {}) {
     const Page = mongoose.model('Page') as unknown as PageModel;
     const Page = mongoose.model('Page') as unknown as PageModel;