Skip to content

Commit

Permalink
♻️ refactor: Refactor services code style (lobehub#5180)
Browse files Browse the repository at this point in the history
* ♻️ refactor: Refactor services code style

* ✅ test: Fix test

* 🐛 fix: Fix review problem
  • Loading branch information
canisminor1990 authored Dec 26, 2024
1 parent df3ac87 commit e98ece8
Show file tree
Hide file tree
Showing 36 changed files with 524 additions and 600 deletions.
2 changes: 1 addition & 1 deletion src/server/routers/lambda/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ export const agentRouter = router({
if (!session) throw new Error('Session not found');
const sessionId = session.id;

return await ctx.agentModel.findBySessionId(sessionId);
return ctx.agentModel.findBySessionId(sessionId);
}),

getKnowledgeBasesAndFiles: agentProcedure
Expand Down
2 changes: 1 addition & 1 deletion src/services/__tests__/chat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -904,7 +904,7 @@ describe('ChatService', () => {
* initialization of AgentRuntime with different providers
*/
vi.mock('../_auth', async (importOriginal) => {
return await importOriginal();
return importOriginal();
});
describe('AgentRuntimeOnClient', () => {
describe('initializeWithClientStore', () => {
Expand Down
2 changes: 1 addition & 1 deletion src/services/_auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ const createAuthTokenWithPayload = async (payload = {}) => {
const accessCode = keyVaultsConfigSelectors.password(useUserStore.getState());
const userId = userProfileSelectors.userId(useUserStore.getState());

return await createJWT<JWTPayload>({ accessCode, userId, ...payload });
return createJWT<JWTPayload>({ accessCode, userId, ...payload });
};

interface AuthParams {
Expand Down
46 changes: 25 additions & 21 deletions src/services/agent.ts
Original file line number Diff line number Diff line change
@@ -1,45 +1,49 @@
import { lambdaClient } from '@/libs/trpc/client';

class AgentService {
async createAgentKnowledgeBase(agentId: string, knowledgeBaseId: string, enabled?: boolean) {
return await lambdaClient.agent.createAgentKnowledgeBase.mutate({
createAgentKnowledgeBase = async (
agentId: string,
knowledgeBaseId: string,
enabled?: boolean,
) => {
return lambdaClient.agent.createAgentKnowledgeBase.mutate({
agentId,
enabled,
knowledgeBaseId,
});
}
};

async deleteAgentKnowledgeBase(agentId: string, knowledgeBaseId: string) {
return await lambdaClient.agent.deleteAgentKnowledgeBase.mutate({ agentId, knowledgeBaseId });
}
deleteAgentKnowledgeBase = async (agentId: string, knowledgeBaseId: string) => {
return lambdaClient.agent.deleteAgentKnowledgeBase.mutate({ agentId, knowledgeBaseId });
};

async toggleKnowledgeBase(agentId: string, knowledgeBaseId: string, enabled?: boolean) {
return await lambdaClient.agent.toggleKnowledgeBase.mutate({
toggleKnowledgeBase = async (agentId: string, knowledgeBaseId: string, enabled?: boolean) => {
return lambdaClient.agent.toggleKnowledgeBase.mutate({
agentId,
enabled,
knowledgeBaseId,
});
}
};

async createAgentFiles(agentId: string, fileIds: string[], enabled?: boolean) {
return await lambdaClient.agent.createAgentFiles.mutate({ agentId, enabled, fileIds });
}
createAgentFiles = async (agentId: string, fileIds: string[], enabled?: boolean) => {
return lambdaClient.agent.createAgentFiles.mutate({ agentId, enabled, fileIds });
};

async deleteAgentFile(agentId: string, fileId: string) {
return await lambdaClient.agent.deleteAgentFile.mutate({ agentId, fileId });
}
deleteAgentFile = async (agentId: string, fileId: string) => {
return lambdaClient.agent.deleteAgentFile.mutate({ agentId, fileId });
};

async toggleFile(agentId: string, fileId: string, enabled?: boolean) {
return await lambdaClient.agent.toggleFile.mutate({
toggleFile = async (agentId: string, fileId: string, enabled?: boolean) => {
return lambdaClient.agent.toggleFile.mutate({
agentId,
enabled,
fileId,
});
}
};

async getFilesAndKnowledgeBases(agentId: string) {
return await lambdaClient.agent.getKnowledgeBasesAndFiles.query({ agentId });
}
getFilesAndKnowledgeBases = async (agentId: string) => {
return lambdaClient.agent.getKnowledgeBasesAndFiles.query({ agentId });
};
}

export const agentService = new AgentService();
4 changes: 2 additions & 2 deletions src/services/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -499,7 +499,7 @@ class ChatService {
return this.reorderToolMessages(postMessages);
};

private mapTrace(trace?: TracePayload, tag?: TraceTagMap): TracePayload {
private mapTrace = (trace?: TracePayload, tag?: TraceTagMap): TracePayload => {
const tags = sessionMetaSelectors.currentAgentMeta(useSessionStore.getState()).tags || [];

const enabled = preferenceSelectors.userAllowTrace(useUserStore.getState());
Expand All @@ -512,7 +512,7 @@ class ChatService {
tags: [tag, ...(trace?.tags || []), ...tags].filter(Boolean) as string[],
userId: userProfileSelectors.userId(useUserStore.getState()),
};
}
};

/**
* Fetch chat completion on the client side.
Expand Down
12 changes: 6 additions & 6 deletions src/services/file/ClientS3/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,21 @@ export class BrowserS3Storage {
* @param key 文件 hash
* @param file File 对象
*/
async putObject(key: string, file: File): Promise<void> {
putObject = async (key: string, file: File): Promise<void> => {
try {
const data = await file.arrayBuffer();
await set(key, { data, name: file.name, type: file.type }, this.store);
} catch (e) {
throw new Error(`Failed to put file ${file.name}: ${(e as Error).message}`);
}
}
};

/**
* 获取文件
* @param key 文件 hash
* @returns File 对象
*/
async getObject(key: string): Promise<File | undefined> {
getObject = async (key: string): Promise<File | undefined> => {
try {
const res = await get<{ data: ArrayBuffer; name: string; type: string }>(key, this.store);
if (!res) return;
Expand All @@ -40,19 +40,19 @@ export class BrowserS3Storage {
} catch (e) {
throw new Error(`Failed to get object (key=${key}): ${(e as Error).message}`);
}
}
};

/**
* 删除文件
* @param key 文件 hash
*/
async deleteObject(key: string): Promise<void> {
deleteObject = async (key: string): Promise<void> => {
try {
await del(key, this.store);
} catch (e) {
throw new Error(`Failed to delete object (key=${key}): ${(e as Error).message}`);
}
}
};
}

export const clientS3Storage = new BrowserS3Storage();
29 changes: 14 additions & 15 deletions src/services/file/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { clientDB } from '@/database/client/db';
import { FileModel } from '@/database/server/models/file';
import { BaseClientService } from '@/services/baseClientService';
import { clientS3Storage } from '@/services/file/ClientS3';
import { FileItem, UploadFileParams } from '@/types/files';

import { IFileService } from './type';

Expand All @@ -11,7 +10,7 @@ export class ClientService extends BaseClientService implements IFileService {
return new FileModel(clientDB as any, this.userId);
}

async createFile(file: UploadFileParams) {
createFile: IFileService['createFile'] = async (file) => {
// save to local storage
// we may want to save to a remote server later
const res = await this.fileModel.create(
Expand All @@ -34,9 +33,9 @@ export class ClientService extends BaseClientService implements IFileService {
id: res.id,
url: `data:${file.fileType};base64,${base64}`,
};
}
};

async getFile(id: string): Promise<FileItem> {
getFile: IFileService['getFile'] = async (id) => {
const item = await this.fileModel.findById(id);
if (!item) {
throw new Error('file not found');
Expand All @@ -57,28 +56,28 @@ export class ClientService extends BaseClientService implements IFileService {
updatedAt: new Date(item.updatedAt),
url,
};
}
};

async removeFile(id: string) {
removeFile: IFileService['removeFile'] = async (id) => {
await this.fileModel.delete(id, false);
}
};

async removeFiles(ids: string[]) {
removeFiles: IFileService['removeFiles'] = async (ids) => {
await this.fileModel.deleteMany(ids, false);
}
};

async removeAllFiles() {
removeAllFiles: IFileService['removeAllFiles'] = async () => {
return this.fileModel.clear();
}
};

async checkFileHash(hash: string) {
checkFileHash: IFileService['checkFileHash'] = async (hash) => {
return this.fileModel.checkHash(hash);
}
};

private async getBase64ByFileHash(hash: string) {
private getBase64ByFileHash = async (hash: string) => {
const fileItem = await clientS3Storage.getObject(hash);
if (!fileItem) throw new Error('file not found');

return Buffer.from(await fileItem.arrayBuffer()).toString('base64');
}
};
}
45 changes: 20 additions & 25 deletions src/services/file/server.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
import { lambdaClient } from '@/libs/trpc/client';
import {
FileItem,
QueryFileListParams,
QueryFileListSchemaType,
UploadFileParams,
} from '@/types/files';
import { QueryFileListParams, QueryFileListSchemaType, UploadFileParams } from '@/types/files';

import { IFileService } from './type';

Expand All @@ -14,45 +9,45 @@ interface CreateFileParams extends Omit<UploadFileParams, 'url'> {
}

export class ServerService implements IFileService {
async createFile(params: UploadFileParams, knowledgeBaseId?: string) {
createFile: IFileService['createFile'] = async (params, knowledgeBaseId) => {
return lambdaClient.file.createFile.mutate({ ...params, knowledgeBaseId } as CreateFileParams);
}
};

async getFile(id: string): Promise<FileItem> {
getFile: IFileService['getFile'] = async (id) => {
const item = await lambdaClient.file.findById.query({ id });

if (!item) {
throw new Error('file not found');
}

return { ...item, type: item.fileType };
}
};

async removeFile(id: string) {
removeFile: IFileService['removeFile'] = async (id) => {
await lambdaClient.file.removeFile.mutate({ id });
}
};

async removeFiles(ids: string[]) {
removeFiles: IFileService['removeFiles'] = async (ids) => {
await lambdaClient.file.removeFiles.mutate({ ids });
}
};

async removeAllFiles() {
removeAllFiles: IFileService['removeAllFiles'] = async () => {
await lambdaClient.file.removeAllFiles.mutate();
}
};

async getFiles(params: QueryFileListParams) {
getFiles = async (params: QueryFileListParams) => {
return lambdaClient.file.getFiles.query(params as QueryFileListSchemaType);
}
};

async getFileItem(id: string) {
getFileItem = async (id: string) => {
return lambdaClient.file.getFileItemById.query({ id });
}
};

async checkFileHash(hash: string) {
checkFileHash: IFileService['checkFileHash'] = async (hash) => {
return lambdaClient.file.checkFileHash.mutate({ hash });
}
};

async removeFileAsyncTask(id: string, type: 'embedding' | 'chunk') {
return await lambdaClient.file.removeFileAsyncTask.mutate({ id, type });
}
removeFileAsyncTask = async (id: string, type: 'embedding' | 'chunk') => {
return lambdaClient.file.removeFileAsyncTask.mutate({ id, type });
};
}
11 changes: 6 additions & 5 deletions src/services/import/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,20 @@ import { clientDB } from '@/database/client/db';
import { DataImporterRepos } from '@/database/repositories/dataImporter';
import { BaseClientService } from '@/services/baseClientService';
import { useUserStore } from '@/store/user';
import { ImportStage, ImporterEntryData, OnImportCallbacks } from '@/types/importer';
import { UserSettings } from '@/types/user/settings';
import { ImportStage } from '@/types/importer';

export class ClientService extends BaseClientService {
import { IImportService } from './type';

export class ClientService extends BaseClientService implements IImportService {
private get dataImporter(): DataImporterRepos {
return new DataImporterRepos(clientDB as any, this.userId);
}

importSettings = async (settings: UserSettings) => {
importSettings: IImportService['importSettings'] = async (settings) => {
await useUserStore.getState().importAppSettings(settings);
};

importData = async (data: ImporterEntryData, callbacks?: OnImportCallbacks) => {
importData: IImportService['importData'] = async (data, callbacks) => {
callbacks?.onStageChange?.(ImportStage.Importing);
const time = Date.now();
try {
Expand Down
11 changes: 6 additions & 5 deletions src/services/import/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,17 @@ import { DefaultErrorShape } from '@trpc/server/unstable-core-do-not-import';

import { edgeClient, lambdaClient } from '@/libs/trpc/client';
import { useUserStore } from '@/store/user';
import { ImportStage, ImporterEntryData, OnImportCallbacks } from '@/types/importer';
import { UserSettings } from '@/types/user/settings';
import { ImportStage, OnImportCallbacks } from '@/types/importer';
import { uuid } from '@/utils/uuid';

export class ServerService {
importSettings = async (settings: UserSettings) => {
import { IImportService } from './type';

export class ServerService implements IImportService {
importSettings: IImportService['importSettings'] = async (settings) => {
await useUserStore.getState().importAppSettings(settings);
};

importData = async (data: ImporterEntryData, callbacks?: OnImportCallbacks): Promise<void> => {
importData: IImportService['importData'] = async (data, callbacks) => {
const handleError = (e: unknown) => {
callbacks?.onStageChange?.(ImportStage.Error);
const error = e as DefaultErrorShape;
Expand Down
7 changes: 7 additions & 0 deletions src/services/import/type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { ImporterEntryData, OnImportCallbacks } from '@/types/importer';
import { UserSettings } from '@/types/user/settings';

export interface IImportService {
importData(data: ImporterEntryData, callbacks?: OnImportCallbacks): Promise<void>;
importSettings(settings: UserSettings): Promise<void>;
}
Loading

0 comments on commit e98ece8

Please sign in to comment.