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

Implement static method to get AiAssistant from pagePaths

Shun Miyazawa 1 год назад
Родитель
Сommit
23f604ae10
1 измененных файлов с 46 добавлено и 2 удалено
  1. 46 2
      apps/app/src/features/openai/server/models/ai-assistant.ts

+ 46 - 2
apps/app/src/features/openai/server/models/ai-assistant.ts

@@ -1,4 +1,5 @@
 import { type IGrantedGroup, GroupType } from '@growi/core';
+import { pathUtils } from '@growi/core/dist/utils';
 import { type Model, type Document, Schema } from 'mongoose';
 
 import { getOrCreateModel } from '~/server/util/mongoose-utils';
@@ -7,8 +8,9 @@ import { type AiAssistant, AiAssistantShareScope, AiAssistantAccessScope } from
 
 export interface AiAssistantDocument extends AiAssistant, Document {}
 
-type AiAssistantModel = Model<AiAssistantDocument>
-
+interface AiAssistantModel extends Model<AiAssistantDocument> {
+  findByPagePaths(pagePaths: string[]): Promise<AiAssistantDocument[]>;
+}
 
 /*
  * Schema Definition
@@ -103,4 +105,46 @@ const schema = new Schema<AiAssistantDocument>(
   },
 );
 
+
+schema.statics.findByPagePaths = async function(pagePaths: string[]): Promise<AiAssistantDocument[]> {
+  /**
+  * @example
+  * // Input: '/Sandbox/Bootstrap5/'
+  * // Output: ['/Sandbox/*', '/Sandbox/Bootstrap5/*']
+  *
+  * // Input: '/user/admin/memo/'
+  * // Output: ['/user/*', '/user/admin/*', '/user/admin/memo/*']
+  */
+  const generateGlobPatterns = (path: string) => {
+  // Remove trailing slash if exists
+    const normalizedPath = pathUtils.removeTrailingSlash(path);
+
+    // Split path into segments
+    const segments = normalizedPath.split('/').filter(Boolean);
+
+    // Generate patterns
+    const patterns: string[] = [];
+    let currentPath = '';
+
+    for (let i = 0; i < segments.length; i++) {
+      currentPath += `/${segments[i]}`;
+      patterns.push(`${currentPath}/*`);
+    }
+
+    return patterns;
+  };
+
+  const pagePathsWithGlobPattern = pagePaths.map(pagePath => generateGlobPatterns(pagePath)).flat();
+  const assistants = await this.find({
+    $or: [
+      // Case 1: Exact match
+      { pagePathPatterns: { $in: pagePaths } },
+      // Case 2: Glob pattern match
+      { pagePathPatterns: { $in: pagePathsWithGlobPattern } },
+    ],
+  }).populate('vectorStore');
+
+  return assistants;
+};
+
 export default getOrCreateModel<AiAssistantDocument, AiAssistantModel>('AiAssistant', schema);