Skip to content

Commit

Permalink
refactor the server model implement
Browse files Browse the repository at this point in the history
  • Loading branch information
arvinxx committed Dec 3, 2024
1 parent fad7dc9 commit 0fd6ac6
Show file tree
Hide file tree
Showing 51 changed files with 430 additions and 383 deletions.
3 changes: 2 additions & 1 deletion src/app/(main)/repos/[id]/@menu/default.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { notFound } from 'next/navigation';
import { Flexbox } from 'react-layout-kit';

import { serverDB } from '@/database/server';
import { KnowledgeBaseModel } from '@/database/server/models/knowledgeBase';

import Head from './Head';
Expand All @@ -14,7 +15,7 @@ type Props = { params: Params };

const MenuPage = async ({ params }: Props) => {
const id = params.id;
const item = await KnowledgeBaseModel.findById(params.id);
const item = await KnowledgeBaseModel.findById(serverDB, params.id);

if (!item) return notFound();

Expand Down
3 changes: 2 additions & 1 deletion src/app/(main)/repos/[id]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { redirect } from 'next/navigation';

import { serverDB } from '@/database/server';
import { KnowledgeBaseModel } from '@/database/server/models/knowledgeBase';
import FileManager from '@/features/FileManager';

Expand All @@ -10,7 +11,7 @@ interface Params {
type Props = { params: Params };

export default async ({ params }: Props) => {
const item = await KnowledgeBaseModel.findById(params.id);
const item = await KnowledgeBaseModel.findById(serverDB, params.id);

if (!item) return redirect('/repos');

Expand Down
4 changes: 0 additions & 4 deletions src/config/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ export const getServerDBConfig = () => {
DATABASE_TEST_URL: process.env.DATABASE_TEST_URL,
DATABASE_URL: process.env.DATABASE_URL,

DISABLE_REMOVE_GLOBAL_FILE: process.env.DISABLE_REMOVE_GLOBAL_FILE === '1',

KEY_VAULTS_SECRET: process.env.KEY_VAULTS_SECRET,

NEXT_PUBLIC_ENABLED_SERVER_SERVICE: process.env.NEXT_PUBLIC_SERVICE_MODE === 'server',
Expand All @@ -22,8 +20,6 @@ export const getServerDBConfig = () => {
DATABASE_TEST_URL: z.string().optional(),
DATABASE_URL: z.string().optional(),

DISABLE_REMOVE_GLOBAL_FILE: z.boolean().optional(),

KEY_VAULTS_SECRET: z.string().optional(),
},
});
Expand Down
4 changes: 2 additions & 2 deletions src/database/server/models/__tests__/_test_template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ vi.mock('@/database/server/core/db', async () => ({
}));

const userId = 'session-group-model-test-user-id';
const sessionGroupModel = new SessionGroupModel(userId);
const sessionGroupModel = new SessionGroupModel(serverDB, userId);

beforeEach(async () => {
await serverDB.delete(users);
Expand Down Expand Up @@ -74,7 +74,7 @@ describe('SessionGroupModel', () => {
await sessionGroupModel.create({ name: 'Test Group 1' });
await sessionGroupModel.create({ name: 'Test Group 333' });

const anotherSessionGroupModel = new SessionGroupModel('user2');
const anotherSessionGroupModel = new SessionGroupModel(serverDB, 'user2');
await anotherSessionGroupModel.create({ name: 'Test Group 2' });

await sessionGroupModel.deleteAll();
Expand Down
2 changes: 1 addition & 1 deletion src/database/server/models/__tests__/agent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ vi.mock('@/database/server/core/db', async () => ({
}));

const userId = 'agent-model-test-user-id';
const agentModel = new AgentModel(userId);
const agentModel = new AgentModel(serverDB, userId);

const knowledgeBase = { id: 'kb1', userId, name: 'knowledgeBase' };
const fileList = [
Expand Down
2 changes: 1 addition & 1 deletion src/database/server/models/__tests__/asyncTask.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ vi.mock('@/database/server/core/db', async () => ({
}));

const userId = 'async-task-model-test-user-id';
const asyncTaskModel = new AsyncTaskModel(userId);
const asyncTaskModel = new AsyncTaskModel(serverDB, userId);

beforeEach(async () => {
await serverDB.delete(users);
Expand Down
2 changes: 1 addition & 1 deletion src/database/server/models/__tests__/chunk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ vi.mock('@/database/server/core/db', async () => ({
}));

const userId = 'chunk-model-test-user-id';
const chunkModel = new ChunkModel(userId);
const chunkModel = new ChunkModel(serverDB, userId);
const sharedFileList = [
{
id: '1',
Expand Down
2 changes: 1 addition & 1 deletion src/database/server/models/__tests__/file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ vi.mock('@/config/db', async () => ({
}));

const userId = 'file-model-test-user-id';
const fileModel = new FileModel(userId);
const fileModel = new FileModel(serverDB, userId);

const knowledgeBase = { id: 'kb1', userId, name: 'knowledgeBase' };
beforeEach(async () => {
Expand Down
10 changes: 5 additions & 5 deletions src/database/server/models/__tests__/knowledgeBase.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ vi.mock('@/database/server/core/db', async () => ({
}));

const userId = 'session-group-model-test-user-id';
const knowledgeBaseModel = new KnowledgeBaseModel(userId);
const knowledgeBaseModel = new KnowledgeBaseModel(serverDB, userId);

beforeEach(async () => {
await serverDB.delete(users);
Expand Down Expand Up @@ -82,7 +82,7 @@ describe('KnowledgeBaseModel', () => {
await knowledgeBaseModel.create({ name: 'Test Group 1' });
await knowledgeBaseModel.create({ name: 'Test Group 333' });

const anotherSessionGroupModel = new KnowledgeBaseModel('user2');
const anotherSessionGroupModel = new KnowledgeBaseModel(serverDB, 'user2');
await anotherSessionGroupModel.create({ name: 'Test Group 2' });

await knowledgeBaseModel.deleteAll();
Expand Down Expand Up @@ -235,7 +235,7 @@ describe('KnowledgeBaseModel', () => {
it('should find a knowledge base by id without user restriction', async () => {
const { id } = await knowledgeBaseModel.create({ name: 'Test Group' });

const group = await KnowledgeBaseModel.findById(id);
const group = await KnowledgeBaseModel.findById(serverDB, id);
expect(group).toMatchObject({
id,
name: 'Test Group',
Expand All @@ -244,10 +244,10 @@ describe('KnowledgeBaseModel', () => {
});

it('should find a knowledge base created by another user', async () => {
const anotherKnowledgeBaseModel = new KnowledgeBaseModel('user2');
const anotherKnowledgeBaseModel = new KnowledgeBaseModel(serverDB, 'user2');
const { id } = await anotherKnowledgeBaseModel.create({ name: 'Another User Group' });

const group = await KnowledgeBaseModel.findById(id);
const group = await KnowledgeBaseModel.findById(serverDB, id);
expect(group).toMatchObject({
id,
name: 'Another User Group',
Expand Down
2 changes: 1 addition & 1 deletion src/database/server/models/__tests__/message.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ vi.mock('@/database/server/core/db', async () => ({
}));

const userId = 'message-db';
const messageModel = new MessageModel(userId);
const messageModel = new MessageModel(serverDB, userId);

beforeEach(async () => {
// 在每个测试用例之前,清空表
Expand Down
2 changes: 1 addition & 1 deletion src/database/server/models/__tests__/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ vi.mock('@/database/server/core/db', async () => ({
}));

const userId = 'plugin-db';
const pluginModel = new PluginModel(userId);
const pluginModel = new PluginModel(serverDB, userId);

beforeEach(async () => {
await serverDB.transaction(async (trx) => {
Expand Down
12 changes: 9 additions & 3 deletions src/database/server/models/__tests__/session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ vi.mock('@/database/server/core/db', async () => ({
}));

const userId = 'session-user';
const sessionModel = new SessionModel(userId);
const sessionModel = new SessionModel(serverDB, userId);

beforeEach(async () => {
await serverDB.delete(users);
Expand Down Expand Up @@ -259,7 +259,13 @@ describe('SessionModel', () => {
]);

await serverDB.insert(agents).values([
{ id: 'agent-1', userId, model: 'gpt-3.5-turbo', title: 'Agent 1', description: 'Description with Keyword' },
{
id: 'agent-1',
userId,
model: 'gpt-3.5-turbo',
title: 'Agent 1',
description: 'Description with Keyword',
},
{ id: 'agent-2', userId, model: 'gpt-4', title: 'Agent 2' },
]);

Expand Down Expand Up @@ -338,7 +344,7 @@ describe('SessionModel', () => {
});
});

describe.skip('batchCreate', () => {
describe('batchCreate', () => {
it('should batch create sessions', async () => {
// 调用 batchCreate 方法
const sessions: NewSession[] = [
Expand Down
4 changes: 2 additions & 2 deletions src/database/server/models/__tests__/sessionGroup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ vi.mock('@/database/server/core/db', async () => ({
}));

const userId = 'session-group-model-test-user-id';
const sessionGroupModel = new SessionGroupModel(userId);
const sessionGroupModel = new SessionGroupModel(serverDB, userId);

beforeEach(async () => {
await serverDB.delete(users);
Expand Down Expand Up @@ -75,7 +75,7 @@ describe('SessionGroupModel', () => {
await sessionGroupModel.create({ name: 'Test Group 1' });
await sessionGroupModel.create({ name: 'Test Group 333' });

const anotherSessionGroupModel = new SessionGroupModel('user2');
const anotherSessionGroupModel = new SessionGroupModel(serverDB, 'user2');
await anotherSessionGroupModel.create({ name: 'Test Group 2' });

await sessionGroupModel.deleteAll();
Expand Down
30 changes: 16 additions & 14 deletions src/database/server/models/__tests__/user.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ vi.mock('@/database/server/core/db', async () => ({

const userId = 'user-db';
const userEmail = '[email protected]';
const userModel = new UserModel();
const userModel = new UserModel(serverDB, userId);

beforeEach(async () => {
await serverDB.delete(users);
Expand All @@ -44,14 +44,14 @@ describe('UserModel', () => {
email: '[email protected]',
};

await UserModel.createUser(params);
await UserModel.createUser(serverDB, params);

const user = await serverDB.query.users.findFirst({ where: eq(users.id, userId) });
expect(user).not.toBeNull();
expect(user?.username).toBe('testuser');
expect(user?.email).toBe('[email protected]');

const sessionModel = new SessionModel(userId);
const sessionModel = new SessionModel(serverDB, userId);
const inbox = await sessionModel.findByIdOrSlug(INBOX_SESSION_ID);
expect(inbox).not.toBeNull();
});
Expand All @@ -61,7 +61,7 @@ describe('UserModel', () => {
it('should delete a user', async () => {
await serverDB.insert(users).values({ id: userId });

await UserModel.deleteUser(userId);
await UserModel.deleteUser(serverDB, userId);

const user = await serverDB.query.users.findFirst({ where: eq(users.id, userId) });
expect(user).toBeUndefined();
Expand All @@ -72,7 +72,7 @@ describe('UserModel', () => {
it('should find a user by ID', async () => {
await serverDB.insert(users).values({ id: userId, username: 'testuser' });

const user = await UserModel.findById(userId);
const user = await UserModel.findById(serverDB, userId);

expect(user).not.toBeNull();
expect(user?.id).toBe(userId);
Expand All @@ -84,7 +84,7 @@ describe('UserModel', () => {
it('should find a user by email', async () => {
await serverDB.insert(users).values({ id: userId, email: userEmail });

const user = await UserModel.findByEmail(userEmail);
const user = await UserModel.findByEmail(serverDB, userEmail);

expect(user).not.toBeNull();
expect(user?.id).toBe(userId);
Expand All @@ -107,23 +107,25 @@ describe('UserModel', () => {
keyVaults: encryptedKeyVaults,
});

const state = await userModel.getUserState(userId);
const state = await userModel.getUserState();

expect(state.userId).toBe(userId);
expect(state.preference).toEqual(preference);
expect(state.settings.keyVaults).toEqual(keyVaults);
});

it('should throw an error if user not found', async () => {
await expect(userModel.getUserState('invalid-user-id')).rejects.toThrow('user not found');
const userModel = new UserModel(serverDB, 'invalid-user-id');

await expect(userModel.getUserState()).rejects.toThrow('user not found');
});
});

describe('updateUser', () => {
it('should update user fields', async () => {
await serverDB.insert(users).values({ id: userId, username: 'oldname' });

await userModel.updateUser(userId, { username: 'newname' });
await userModel.updateUser({ username: 'newname' });

const updatedUser = await serverDB.query.users.findFirst({
where: eq(users.id, userId),
Expand All @@ -137,7 +139,7 @@ describe('UserModel', () => {
await serverDB.insert(users).values({ id: userId });
await serverDB.insert(userSettings).values({ id: userId });

await userModel.deleteSetting(userId);
await userModel.deleteSetting();

const settings = await serverDB.query.userSettings.findFirst({
where: eq(users.id, userId),
Expand All @@ -155,7 +157,7 @@ describe('UserModel', () => {
} as UserSettings;
await serverDB.insert(users).values({ id: userId });

await userModel.updateSetting(userId, settings);
await userModel.updateSetting(settings);

const updatedSettings = await serverDB.query.userSettings.findFirst({
where: eq(users.id, userId),
Expand All @@ -178,7 +180,7 @@ describe('UserModel', () => {
const newSettings = {
general: { fontSize: 16, language: 'zh-CN', themeMode: 'dark' },
} as UserSettings;
await userModel.updateSetting(userId, newSettings);
await userModel.updateSetting(newSettings);

const updatedSettings = await serverDB.query.userSettings.findFirst({
where: eq(users.id, userId),
Expand All @@ -195,7 +197,7 @@ describe('UserModel', () => {
const newPreference: Partial<UserPreference> = {
guide: { topic: true, moveSettingsToAvatar: true },
};
await userModel.updatePreference(userId, newPreference);
await userModel.updatePreference(newPreference);

const updatedUser = await serverDB.query.users.findFirst({ where: eq(users.id, userId) });
expect(updatedUser?.preference).toEqual({ ...preference, ...newPreference });
Expand All @@ -212,7 +214,7 @@ describe('UserModel', () => {
moveSettingsToAvatar: true,
uploadFileInKnowledgeBase: true,
};
await userModel.updateGuide(userId, newGuide);
await userModel.updateGuide(newGuide);

const updatedUser = await serverDB.query.users.findFirst({ where: eq(users.id, userId) });
expect(updatedUser?.preference).toEqual({ ...preference, guide: newGuide });
Expand Down
Loading

0 comments on commit 0fd6ac6

Please sign in to comment.