feat: 修改chat的数据结构

This commit is contained in:
Archer
2023-03-18 00:49:44 +08:00
parent e6c9ca540a
commit 38c093d9ae
33 changed files with 2631 additions and 341 deletions

View File

@@ -1,12 +1,13 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { jsonRes } from '@/service/response';
import { connectToDatabase, Chat, ChatWindow } from '@/service/mongo';
import type { ModelType } from '@/types/model';
import { connectToDatabase, Chat } from '@/service/mongo';
import type { ChatPopulate } from '@/types/mongoSchema';
import type { InitChatResponse } from '@/api/response/chat';
/* 获取我的模型 */
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const { chatId, windowId } = req.query as { chatId: string; windowId?: string };
const { chatId } = req.query as { chatId: string };
if (!chatId) {
throw new Error('缺少参数');
@@ -15,16 +16,15 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
await connectToDatabase();
// 获取 chat 数据
const chat = await Chat.findById(chatId).populate({
const chat = await Chat.findById<ChatPopulate>(chatId).populate({
path: 'modelId',
options: {
strictPopulate: false
}
});
// 安全校验
if (!chat || chat.loadAmount === 0 || chat.expiredTime < Date.now()) {
throw new Error('聊天框已过期');
if (!chat) {
throw new Error('聊天框不存在');
}
if (chat.loadAmount > 0) {
@@ -38,38 +38,18 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
);
}
const model: ModelType = chat.modelId;
/* 查找是否有记录 */
let history = null;
let responseId = windowId;
try {
history = await ChatWindow.findById(windowId);
} catch (error) {
error;
}
if (!history) {
// 没有记录,创建一个
const response = await ChatWindow.create({
chatId,
updateTime: Date.now(),
content: []
});
responseId = response._id;
}
jsonRes(res, {
const model = chat.modelId;
jsonRes<InitChatResponse>(res, {
code: 201,
data: {
windowId: responseId,
chatSite: {
modelId: model._id,
name: model.name,
avatar: model.avatar,
secret: model.security,
chatModel: model.service.chatModel
},
history: history ? history.content : []
chatId: chat._id,
isExpiredTime: chat.loadAmount === 0 || chat.expiredTime <= Date.now(),
modelId: model._id,
name: model.name,
avatar: model.avatar,
secret: model.security,
chatModel: model.service.chatModel,
history: chat.content
}
});
} catch (err) {