Просмотр исходного кода

re-impl removePageRedirectsByToPath

Yuki Takei 3 лет назад
Родитель
Сommit
b76bf7716d

+ 27 - 6
packages/app/src/server/models/page-redirect.ts

@@ -78,14 +78,35 @@ schema.statics.retrievePageRedirectEndpoints = async function(fromPath: string):
   return { start, end };
 };
 
-schema.statics.removePageRedirectByToPath = async function(toPath: string): Promise<void> {
-  await this.deleteMany({ toPath });
+schema.statics.removePageRedirectsByToPath = async function(toPath: string): Promise<void> {
+  const aggResult: IPageRedirectWithChains[] = await this.aggregate([
+    { $match: { toPath } },
+    {
+      $graphLookup: {
+        from: 'pageredirects',
+        startWith: '$fromPath',
+        connectFromField: 'fromPath',
+        connectToField: 'toPath',
+        as: CHAINS_FIELD_NAME,
+      },
+    },
+  ]);
+
+  if (aggResult.length === 0) {
+    return;
+  }
+
+  const idsToRemove = aggResult
+    .map((redirectWithChains) => {
+      return [
+        redirectWithChains._id,
+        redirectWithChains[CHAINS_FIELD_NAME].map(doc => doc._id),
+      ].flat();
+    })
+    .flat();
 
+  await this.deleteMany({ _id: { $in: idsToRemove } });
   return;
 };
 
-// schema.statics.removePageRedirectsByChains = async function(redirectChains: IPageRedirectChains): Promise<void> {
-//   return;
-// };
-
 export default getOrCreateModel<PageRedirectDocument, PageRedirectModel>('PageRedirect', schema);

+ 1 - 1
packages/app/src/server/routes/page.js

@@ -1476,7 +1476,7 @@ module.exports = function(crowi, app) {
     const path = req.body.path;
 
     try {
-      await PageRedirect.removePageRedirectByToPath(path);
+      await PageRedirect.removePageRedirectsByToPath(path);
       logger.debug('Redirect Page deleted', path);
     }
     catch (err) {

+ 2 - 2
packages/app/test/integration/models/page-redirect.test.js

@@ -19,7 +19,7 @@ describe('PageRedirect', () => {
     await PageRedirect.deleteMany({});
   });
 
-  describe('.removePageRedirectByToPath', () => {
+  describe('.removePageRedirectsByToPath', () => {
     test('works fine', async() => {
       // setup:
       await PageRedirect.insertMany([
@@ -37,7 +37,7 @@ describe('PageRedirect', () => {
 
       // when:
       // remove all documents that have { toPath: '/path/3' }
-      await PageRedirect.removePageRedirectByToPath('/path3');
+      await PageRedirect.removePageRedirectsByToPath('/path3');
 
       // then:
       expect(await PageRedirect.findOne({ fromPath: '/org/path1' })).not.toBeNull();