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

refactor add-depth-condition.ts

Yuki Takei 2 лет назад
Родитель
Сommit
2c7ffa957d

+ 11 - 18
packages/remark-lsx/src/server/routes/list-pages/add-depth-condition.ts

@@ -1,21 +1,17 @@
-import { OptionParser } from '@growi/core/dist/plugin';
-import { pagePathUtils } from '@growi/core/dist/utils';
+import type { ParseRangeResult } from '@growi/core';
 import createError from 'http-errors';
 
-import type { PageQuery } from './generate-base-query';
-
-const { isTopPage } = pagePathUtils;
+import { getDepthOfPath } from '../../../utils/depth-utils';
 
-export const addDepthCondition = (query: PageQuery, pagePath: string, optionsDepth: string): PageQuery => {
+import type { PageQuery } from './generate-base-query';
 
-  const range = OptionParser.parseRange(optionsDepth);
+export const addDepthCondition = (query: PageQuery, pagePath: string, depthRange: ParseRangeResult | null): PageQuery => {
 
-  if (range == null) {
+  if (depthRange == null) {
     return query;
   }
 
-  const start = range.start;
-  const end = range.end;
+  const { start, end } = depthRange;
 
   // check start
   if (start < 1) {
@@ -26,20 +22,17 @@ export const addDepthCondition = (query: PageQuery, pagePath: string, optionsDep
     throw createError(400, `The specified option 'depth' is { start: ${start}, end: ${end} } : the end must be larger or equal than the start`);
   }
 
-  // count slash
-  const slashNum = isTopPage(pagePath)
-    ? 1
-    : pagePath.split('/').length;
-  const depthStart = slashNum + start - 1;
-  const depthEnd = slashNum + end - 1;
+  const depthOfPath = getDepthOfPath(pagePath);
+  const slashNumStart = depthOfPath + depthRange.start;
+  const slashNumEnd = depthOfPath + depthRange.end;
 
   if (end < 0) {
     return query.and([
-      { path: new RegExp(`^(\\/[^\\/]*){${depthStart},}$`) },
+      { path: new RegExp(`^(\\/[^\\/]*){${slashNumStart},}$`) },
     ]);
   }
 
   return query.and([
-    { path: new RegExp(`^(\\/[^\\/]*){${depthStart},${depthEnd}}$`) },
+    { path: new RegExp(`^(\\/[^\\/]*){${slashNumStart},${slashNumEnd}}$`) },
   ]);
 };

+ 2 - 2
packages/remark-lsx/src/server/routes/list-pages/index.ts

@@ -1,5 +1,5 @@
 
-import type { IUser } from '@growi/core';
+import { type IUser, OptionParser } from '@growi/core';
 import { pathUtils } from '@growi/core/dist/utils';
 import escapeStringRegexp from 'escape-string-regexp';
 import type { Request, Response } from 'express';
@@ -89,7 +89,7 @@ export const listPages = async(req: Request & { user: IUser }, res: Response): P
   try {
     // depth
     if (options?.depth != null) {
-      query = addDepthCondition(query, params.pagePath, options.depth);
+      query = addDepthCondition(query, params.pagePath, OptionParser.parseRange(options.depth));
     }
     // filter
     if (options?.filter != null) {