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

Add isDefault field & implement logic to toggle isDefault

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

+ 22 - 0
apps/app/src/features/openai/server/models/ai-assistant.ts

@@ -1,4 +1,5 @@
 import { type IGrantedGroup, GroupType } from '@growi/core';
+import createError from 'http-errors';
 import { type Model, type Document, Schema } from 'mongoose';
 
 import { getOrCreateModel } from '~/server/util/mongoose-utils';
@@ -10,6 +11,7 @@ export interface AiAssistantDocument extends AiAssistant, Document {}
 
 interface AiAssistantModel extends Model<AiAssistantDocument> {
   findByPagePaths(pagePaths: string[]): Promise<AiAssistantDocument[]>;
+  toggleDefault(id: string, isDefault: boolean): Promise<AiAssistantDocument>;
 }
 
 /*
@@ -99,6 +101,11 @@ const schema = new Schema<AiAssistantDocument>(
       enum: Object.values(AiAssistantAccessScope),
       required: true,
     },
+    isDefault: {
+      type: Boolean,
+      required: true,
+      default: false,
+    },
   },
   {
     timestamps: true,
@@ -120,4 +127,19 @@ schema.statics.findByPagePaths = async function(pagePaths: string[]): Promise<Ai
   return assistants;
 };
 
+schema.statics.toggleDefault = async function(id: string, isDefault: boolean): Promise<AiAssistantDocument> {
+  const aiAssistant = await this.findOne({ _id: id, shareScope: AiAssistantAccessScope.PUBLIC_ONLY });
+  if (aiAssistant == null) {
+    throw createError(404, 'AiAssistant document does not exist');
+  }
+
+  await this.updateMany({ isDefault: true }, { isDefault: false });
+
+  aiAssistant.isDefault = isDefault;
+  const updatedAiAssistant = await aiAssistant.save();
+
+  return updatedAiAssistant;
+};
+
+
 export default getOrCreateModel<AiAssistantDocument, AiAssistantModel>('AiAssistant', schema);