@lobehub/chat 0.147.16 → 0.147.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/contributing/Basic/Feature-Development.md +7 -7
  3. package/contributing/Basic/Feature-Development.zh-CN.md +7 -7
  4. package/next.config.mjs +61 -13
  5. package/package.json +2 -1
  6. package/sentry.client.config.ts +30 -0
  7. package/sentry.edge.config.ts +17 -0
  8. package/sentry.server.config.ts +19 -0
  9. package/src/app/home/Redirect.tsx +2 -2
  10. package/src/database/client/models/__tests__/session.test.ts +1 -3
  11. package/src/database/client/models/session.ts +4 -4
  12. package/src/services/config.ts +4 -4
  13. package/src/services/file/client.test.ts +2 -2
  14. package/src/services/file/client.ts +35 -33
  15. package/src/services/file/index.ts +8 -2
  16. package/src/services/file/type.ts +11 -0
  17. package/src/services/message/client.test.ts +6 -32
  18. package/src/services/message/client.ts +24 -37
  19. package/src/services/message/index.test.ts +48 -0
  20. package/src/services/message/index.ts +22 -2
  21. package/src/services/message/type.ts +33 -0
  22. package/src/services/plugin/client.test.ts +2 -2
  23. package/src/services/plugin/client.ts +1 -1
  24. package/src/services/plugin/index.ts +9 -3
  25. package/src/services/session/client.test.ts +37 -44
  26. package/src/services/session/client.ts +30 -22
  27. package/src/services/session/index.ts +9 -2
  28. package/src/services/session/type.ts +44 -0
  29. package/src/services/topic/client.test.ts +18 -22
  30. package/src/services/topic/client.ts +31 -23
  31. package/src/services/topic/index.ts +10 -2
  32. package/src/services/topic/type.ts +32 -0
  33. package/src/services/user/client.ts +1 -1
  34. package/src/services/user/index.ts +10 -2
  35. package/src/store/chat/slices/message/action.test.ts +12 -12
  36. package/src/store/chat/slices/message/action.ts +4 -4
  37. package/src/store/chat/slices/plugin/action.test.ts +5 -6
  38. package/src/store/chat/slices/plugin/action.ts +1 -1
  39. package/src/store/chat/slices/topic/action.test.ts +11 -6
  40. package/src/store/chat/slices/topic/action.ts +7 -5
  41. package/src/store/session/slices/agent/action.test.ts +175 -0
  42. package/src/store/session/slices/agent/action.ts +1 -1
  43. package/src/store/session/slices/session/action.test.ts +14 -15
  44. package/src/store/session/slices/session/action.ts +4 -4
  45. package/src/store/session/slices/sessionGroup/action.test.ts +6 -4
  46. package/src/store/session/slices/sessionGroup/action.ts +3 -3
package/CHANGELOG.md CHANGED
@@ -2,6 +2,31 @@
2
2
 
3
3
  # Changelog
4
4
 
5
+ ### [Version 0.147.17](https://github.com/lobehub/lobe-chat/compare/v0.147.16...v0.147.17)
6
+
7
+ <sup>Released on **2024-04-16**</sup>
8
+
9
+ #### ♻ Code Refactoring
10
+
11
+ - **misc**: Refactor service to a uniform interface.
12
+
13
+ <br/>
14
+
15
+ <details>
16
+ <summary><kbd>Improvements and Fixes</kbd></summary>
17
+
18
+ #### Code refactoring
19
+
20
+ - **misc**: Refactor service to a uniform interface, closes [#2062](https://github.com/lobehub/lobe-chat/issues/2062) ([86779e2](https://github.com/lobehub/lobe-chat/commit/86779e2))
21
+
22
+ </details>
23
+
24
+ <div align="right">
25
+
26
+ [![](https://img.shields.io/badge/-BACK_TO_TOP-151515?style=flat-square)](#readme-top)
27
+
28
+ </div>
29
+
5
30
  ### [Version 0.147.16](https://github.com/lobehub/lobe-chat/compare/v0.147.15...v0.147.16)
6
31
 
7
32
  <sup>Released on **2024-04-14**</sup>
@@ -231,7 +231,7 @@ This requirement involves upgrading the Sessions feature to transform it from a
231
231
 
232
232
  To handle these groups, we need to refactor the implementation logic of `useFetchSessions`. Here are the key changes:
233
233
 
234
- 1. Use the `sessionService.getSessionsWithGroup` method to call the backend API and retrieve the grouped session data.
234
+ 1. Use the `sessionService.getGroupedSessions` method to call the backend API and retrieve the grouped session data.
235
235
  2. Save the retrieved data into three different state fields: `pinnedSessions`, `customSessionGroups`, and `defaultSessions`.
236
236
 
237
237
  #### `useFetchSessions` Method
@@ -247,7 +247,7 @@ export const createSessionSlice: StateCreator<
247
247
  > = (set, get) => ({
248
248
  // ... other methods
249
249
  useFetchSessions: () =>
250
- useSWR<ChatSessionList>(FETCH_SESSIONS_KEY, sessionService.getSessionsWithGroup, {
250
+ useSWR<ChatSessionList>(FETCH_SESSIONS_KEY, sessionService.getGroupedSessions, {
251
251
  onSuccess: (data) => {
252
252
  set(
253
253
  {
@@ -267,15 +267,15 @@ export const createSessionSlice: StateCreator<
267
267
 
268
268
  After successfully retrieving the data, we use the `set` method to update the `customSessionGroups`, `defaultSessions`, `pinnedSessions`, and `sessions` states. This ensures that the states are synchronized with the latest session data.
269
269
 
270
- #### `sessionService.getSessionsWithGroup` Method
270
+ #### `sessionService.getGroupedSessions` Method
271
271
 
272
- The `sessionService.getSessionsWithGroup` method is responsible for calling the backend API `SessionModel.queryWithGroups()`.
272
+ The `sessionService.getGroupedSessions` method is responsible for calling the backend API `SessionModel.queryWithGroups()`.
273
273
 
274
274
  ```typescript
275
275
  class SessionService {
276
276
  // ... other SessionGroup related implementations
277
277
 
278
- async getSessionsWithGroup(): Promise<ChatSessionList> {
278
+ async getGroupedSessions(): Promise<ChatSessionList> {
279
279
  return SessionModel.queryWithGroups();
280
280
  }
281
281
  }
@@ -283,7 +283,7 @@ class SessionService {
283
283
 
284
284
  #### `SessionModel.queryWithGroups` Method
285
285
 
286
- This method is the core method called by `sessionService.getSessionsWithGroup`, and it is responsible for querying and organizing session data. The code is as follows:
286
+ This method is the core method called by `sessionService.getGroupedSessions`, and it is responsible for querying and organizing session data. The code is as follows:
287
287
 
288
288
  ```typescript
289
289
  class _SessionModel extends BaseModel {
@@ -617,7 +617,7 @@ class ConfigService {
617
617
  // ... Other code omitted
618
618
 
619
619
  exportSessions = async () => {
620
- const sessions = await sessionService.getSessions();
620
+ const sessions = await sessionService.getAllSessions();
621
621
  + const sessionGroups = await sessionService.getSessionGroups();
622
622
  const messages = await messageService.getAllMessages();
623
623
  const topics = await topicService.getAllTopics();
@@ -231,7 +231,7 @@ export const createSessionGroupSlice: StateCreator<
231
231
 
232
232
  为了处理这些分组,我们需要改造 `useFetchSessions` 的实现逻辑。以下是关键的改动点:
233
233
 
234
- 1. 使用 `sessionService.getSessionsWithGroup` 方法负责调用后端接口来获取分组后的会话数据;
234
+ 1. 使用 `sessionService.getGroupedSessions` 方法负责调用后端接口来获取分组后的会话数据;
235
235
  2. 将获取后的数据保存为三到不同的状态字段中:`pinnedSessions`、`customSessionGroups` 和 `defaultSessions`;
236
236
 
237
237
  #### `useFetchSessions` 方法
@@ -247,7 +247,7 @@ export const createSessionSlice: StateCreator<
247
247
  > = (set, get) => ({
248
248
  // ... 其他方法
249
249
  useFetchSessions: () =>
250
- useSWR<ChatSessionList>(FETCH_SESSIONS_KEY, sessionService.getSessionsWithGroup, {
250
+ useSWR<ChatSessionList>(FETCH_SESSIONS_KEY, sessionService.getGroupedSessions, {
251
251
  onSuccess: (data) => {
252
252
  set(
253
253
  {
@@ -267,15 +267,15 @@ export const createSessionSlice: StateCreator<
267
267
 
268
268
  在成功获取数据后,我们使用 `set` 方法来更新 `customSessionGroups`、`defaultSessions`、`pinnedSessions` 和 `sessions` 状态。这将保证状态与最新的会话数据同步。
269
269
 
270
- #### getSessionsWithGroup
270
+ #### getGroupedSessions
271
271
 
272
- 使用 `sessionService.getSessionsWithGroup` 方法负责调用后端接口 `SessionModel.queryWithGroups()`
272
+ 使用 `sessionService.getGroupedSessions` 方法负责调用后端接口 `SessionModel.queryWithGroups()`
273
273
 
274
274
  ```typescript
275
275
  class SessionService {
276
276
  // ... 其他 SessionGroup 相关的实现
277
277
 
278
- async getSessionsWithGroup(): Promise<ChatSessionList> {
278
+ async getGroupedSessions(): Promise<ChatSessionList> {
279
279
  return SessionModel.queryWithGroups();
280
280
  }
281
281
  }
@@ -283,7 +283,7 @@ class SessionService {
283
283
 
284
284
  #### `SessionModel.queryWithGroups` 方法
285
285
 
286
- 此方法是 `sessionService.getSessionsWithGroup` 调用的核心方法,它负责查询和组织会话数据,代码如下:
286
+ 此方法是 `sessionService.getGroupedSessions` 调用的核心方法,它负责查询和组织会话数据,代码如下:
287
287
 
288
288
  ```typescript
289
289
  class _SessionModel extends BaseModel {
@@ -611,7 +611,7 @@ class ConfigService {
611
611
  // ... 省略其他
612
612
 
613
613
  exportSessions = async () => {
614
- const sessions = await sessionService.getSessions();
614
+ const sessions = await sessionService.getAllSessions();
615
615
  + const sessionGroups = await sessionService.getSessionGroups();
616
616
  const messages = await messageService.getAllMessages();
617
617
  const topics = await topicService.getAllTopics();
package/next.config.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import nextPWA from '@ducanh2912/next-pwa';
2
2
  import analyzer from '@next/bundle-analyzer';
3
+ import { withSentryConfig } from '@sentry/nextjs';
3
4
 
4
5
  const isProd = process.env.NODE_ENV === 'production';
5
6
  const buildWithDocker = process.env.DOCKER === 'true';
@@ -9,18 +10,6 @@ const API_PROXY_ENDPOINT = process.env.API_PROXY_ENDPOINT || '';
9
10
 
10
11
  const basePath = process.env.NEXT_PUBLIC_BASE_PATH;
11
12
 
12
- const withBundleAnalyzer = analyzer({
13
- enabled: process.env.ANALYZE === 'true',
14
- });
15
-
16
- const withPWA = nextPWA({
17
- dest: 'public',
18
- register: true,
19
- workboxOptions: {
20
- skipWaiting: true,
21
- },
22
- });
23
-
24
13
  /** @type {import('next').NextConfig} */
25
14
  const nextConfig = {
26
15
  compress: isProd,
@@ -67,4 +56,63 @@ const nextConfig = {
67
56
  },
68
57
  };
69
58
 
70
- export default isProd ? withBundleAnalyzer(withPWA(nextConfig)) : nextConfig;
59
+ const noWrapper = (config) => config;
60
+
61
+ const withBundleAnalyzer = process.env.ANALYZE === 'true' ? analyzer() : noWrapper;
62
+
63
+ const withPWA = isProd
64
+ ? nextPWA({
65
+ dest: 'public',
66
+ register: true,
67
+ workboxOptions: {
68
+ skipWaiting: true,
69
+ },
70
+ })
71
+ : noWrapper;
72
+
73
+ const hasSentry = !!process.env.NEXT_PUBLIC_SENTRY_DSN;
74
+ const withSentry =
75
+ isProd && hasSentry
76
+ ? (c) =>
77
+ withSentryConfig(
78
+ c,
79
+ {
80
+ // For all available options, see:
81
+ // https://github.com/getsentry/sentry-webpack-plugin#options
82
+
83
+ // Suppresses source map uploading logs during build
84
+ silent: true,
85
+ org: process.env.SENTRY_ORG,
86
+ project: process.env.SENTRY_PROJECT,
87
+ },
88
+ {
89
+ // For all available options, see:
90
+ // https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/
91
+
92
+ // Upload a larger set of source maps for prettier stack traces (increases build time)
93
+ widenClientFileUpload: true,
94
+
95
+ // Transpiles SDK to be compatible with IE11 (increases bundle size)
96
+ transpileClientSDK: true,
97
+
98
+ // Routes browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers. (increases server load)
99
+ // Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client-
100
+ // side errors will fail.
101
+ tunnelRoute: '/monitoring',
102
+
103
+ // Hides source maps from generated client bundles
104
+ hideSourceMaps: true,
105
+
106
+ // Automatically tree-shake Sentry logger statements to reduce bundle size
107
+ disableLogger: true,
108
+
109
+ // Enables automatic instrumentation of Vercel Cron Monitors.
110
+ // See the following for more information:
111
+ // https://docs.sentry.io/product/crons/
112
+ // https://vercel.com/docs/cron-jobs
113
+ automaticVercelMonitors: true,
114
+ },
115
+ )
116
+ : noWrapper;
117
+
118
+ export default withBundleAnalyzer(withPWA(withSentry(nextConfig)));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lobehub/chat",
3
- "version": "0.147.16",
3
+ "version": "0.147.17",
4
4
  "description": "Lobe Chat - an open-source, high-performance chatbot framework that supports speech synthesis, multimodal, and extensible Function Call plugin system. Supports one-click free deployment of your private ChatGPT/LLM web application.",
5
5
  "keywords": [
6
6
  "framework",
@@ -94,6 +94,7 @@
94
94
  "@lobehub/tts": "latest",
95
95
  "@lobehub/ui": "^1.137.7",
96
96
  "@next/third-parties": "^14.1.4",
97
+ "@sentry/nextjs": "^7.105.0",
97
98
  "@vercel/analytics": "^1.2.2",
98
99
  "@vercel/speed-insights": "^1.0.10",
99
100
  "ahooks": "^3.7.11",
@@ -0,0 +1,30 @@
1
+ // This file configures the initialization of Sentry on the client.
2
+ // The config you add here will be used whenever a users loads a page in their browser.
3
+ // https://docs.sentry.io/platforms/javascript/guides/nextjs/
4
+ import * as Sentry from '@sentry/nextjs';
5
+
6
+ if (!!process.env.NEXT_PUBLIC_SENTRY_DSN) {
7
+ Sentry.init({
8
+ // Setting this option to true will print useful information to the console while you're setting up Sentry.
9
+ debug: false,
10
+
11
+ dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
12
+ // You can remove this option if you're not planning to use the Sentry Session Replay feature:
13
+ integrations: [
14
+ Sentry.replayIntegration({
15
+ blockAllMedia: true,
16
+ // Additional Replay configuration goes in here, for example:
17
+ maskAllText: true,
18
+ }),
19
+ ],
20
+
21
+ replaysOnErrorSampleRate: 1,
22
+
23
+ // This sets the sample rate to be 10%. You may want this to be 100% while
24
+ // in development and sample at a lower rate in production
25
+ replaysSessionSampleRate: 0.1,
26
+
27
+ // Adjust this value in production, or use tracesSampler for greater control
28
+ tracesSampleRate: 1,
29
+ });
30
+ }
@@ -0,0 +1,17 @@
1
+ // This file configures the initialization of Sentry for edge features (middleware, edge routes, and so on).
2
+ // The config you add here will be used whenever one of the edge features is loaded.
3
+ // Note that this config is unrelated to the Vercel Edge Runtime and is also required when running locally.
4
+ // https://docs.sentry.io/platforms/javascript/guides/nextjs/
5
+ import * as Sentry from '@sentry/nextjs';
6
+
7
+ if (!!process.env.NEXT_PUBLIC_SENTRY_DSN) {
8
+ Sentry.init({
9
+ // Setting this option to true will print useful information to the console while you're setting up Sentry.
10
+ debug: false,
11
+
12
+ dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
13
+
14
+ // Adjust this value in production, or use tracesSampler for greater control
15
+ tracesSampleRate: 1,
16
+ });
17
+ }
@@ -0,0 +1,19 @@
1
+ // This file configures the initialization of Sentry on the server.
2
+ // The config you add here will be used whenever the server handles a request.
3
+ // https://docs.sentry.io/platforms/javascript/guides/nextjs/
4
+ import * as Sentry from '@sentry/nextjs';
5
+
6
+ if (!!process.env.NEXT_PUBLIC_SENTRY_DSN) {
7
+ Sentry.init({
8
+ // Setting this option to true will print useful information to the console while you're setting up Sentry.
9
+ debug: false,
10
+
11
+ dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
12
+
13
+ // Adjust this value in production, or use tracesSampler for greater control
14
+ tracesSampleRate: 1,
15
+
16
+ // uncomment the line below to enable Spotlight (https://spotlightjs.com)
17
+ // spotlight: process.env.NODE_ENV === 'development',
18
+ });
19
+ }
@@ -8,8 +8,8 @@ import { sessionService } from '@/services/session';
8
8
 
9
9
  const checkHasConversation = async () => {
10
10
  const hasMessages = await messageService.hasMessages();
11
- const hasAgents = await sessionService.hasSessions();
12
- return hasMessages || hasAgents;
11
+ const hasAgents = await sessionService.countSessions();
12
+ return hasMessages || hasAgents === 0;
13
13
  };
14
14
 
15
15
  const Redirect = memo(() => {
@@ -111,12 +111,10 @@ describe('SessionModel', () => {
111
111
 
112
112
  expect(updatedSession).toHaveProperty('group', 'newGroup');
113
113
  });
114
- });
115
114
 
116
- describe('updatePinned', () => {
117
115
  it('should update pinned status of a session', async () => {
118
116
  const createdSession = await SessionModel.create('agent', sessionData);
119
- await SessionModel.updatePinned(createdSession.id, true);
117
+ await SessionModel.update(createdSession.id, { pinned: 1 });
120
118
  const updatedSession = await SessionModel.findById(createdSession.id);
121
119
  expect(updatedSession).toHaveProperty('pinned', 1);
122
120
  });
@@ -171,6 +171,10 @@ class _SessionModel extends BaseModel {
171
171
  return (await this.table.count()) === 0;
172
172
  }
173
173
 
174
+ async count() {
175
+ return this.table.count();
176
+ }
177
+
174
178
  // **************** Create *************** //
175
179
 
176
180
  async create(type: 'agent' | 'group', defaultValue: Partial<LobeAgentSession>, id = uuid()) {
@@ -238,10 +242,6 @@ class _SessionModel extends BaseModel {
238
242
  return super._updateWithSync(id, data);
239
243
  }
240
244
 
241
- async updatePinned(id: string, pinned: boolean) {
242
- return this.update(id, { pinned: pinned ? 1 : 0 });
243
- }
244
-
245
245
  async updateConfig(id: string, data: DeepPartial<LobeAgentConfig>) {
246
246
  const session = await this.findById(id);
247
247
  if (!session) return;
@@ -33,7 +33,7 @@ class ConfigService {
33
33
  return await sessionService.batchCreateSessions(sessions);
34
34
  };
35
35
  importMessages = async (messages: ChatMessage[]) => {
36
- return messageService.batchCreate(messages);
36
+ return messageService.batchCreateMessages(messages);
37
37
  };
38
38
  importSettings = async (settings: GlobalSettings) => {
39
39
  useGlobalStore.getState().importAppSettings(settings);
@@ -105,7 +105,7 @@ class ConfigService {
105
105
  * export all agents
106
106
  */
107
107
  exportAgents = async () => {
108
- const agents = await sessionService.getAllAgents();
108
+ const agents = await sessionService.getSessionsByType('agent');
109
109
  const sessionGroups = await sessionService.getSessionGroups();
110
110
 
111
111
  const config = createConfigFile('agents', { sessionGroups, sessions: agents });
@@ -117,7 +117,7 @@ class ConfigService {
117
117
  * export all sessions
118
118
  */
119
119
  exportSessions = async () => {
120
- const sessions = await sessionService.getSessions();
120
+ const sessions = await sessionService.getSessionsByType();
121
121
  const sessionGroups = await sessionService.getSessionGroups();
122
122
  const messages = await messageService.getAllMessages();
123
123
  const topics = await topicService.getAllTopics();
@@ -188,7 +188,7 @@ class ConfigService {
188
188
  * export all data
189
189
  */
190
190
  exportAll = async () => {
191
- const sessions = await sessionService.getSessions();
191
+ const sessions = await sessionService.getSessionsByType();
192
192
  const sessionGroups = await sessionService.getSessionGroups();
193
193
  const messages = await messageService.getAllMessages();
194
194
  const topics = await topicService.getAllTopics();
@@ -3,9 +3,9 @@ import { Mock, beforeEach, describe, expect, it, vi } from 'vitest';
3
3
  import { FileModel } from '@/database/client/models/file';
4
4
  import { DB_File } from '@/database/client/schemas/files';
5
5
 
6
- import { FileService } from './client';
6
+ import { ClientService } from './client';
7
7
 
8
- const fileService = new FileService();
8
+ const fileService = new ClientService();
9
9
 
10
10
  // Mocks for the FileModel
11
11
  vi.mock('@/database/client/models/file', () => ({
@@ -4,12 +4,9 @@ import { FilePreview } from '@/types/files';
4
4
  import compressImage from '@/utils/compressImage';
5
5
 
6
6
  import { API_ENDPOINTS } from '../_url';
7
+ import { IFileService } from './type';
7
8
 
8
- export class FileService {
9
- private isImage(fileType: string) {
10
- const imageRegex = /^image\//;
11
- return imageRegex.test(fileType);
12
- }
9
+ export class ClientService implements IFileService {
13
10
  async uploadFile(file: DB_File) {
14
11
  // 跳过图片上传测试
15
12
  const isTestData = file.size === 1;
@@ -22,26 +19,6 @@ export class FileService {
22
19
  return FileModel.create(file);
23
20
  }
24
21
 
25
- async uploadImageFile(file: DB_File) {
26
- // 加载图片
27
- const url = file.url || URL.createObjectURL(new Blob([file.data]));
28
-
29
- const img = new Image();
30
- img.src = url;
31
- await (() =>
32
- new Promise((resolve) => {
33
- img.addEventListener('load', resolve);
34
- }))();
35
-
36
- // 压缩图片
37
- const base64String = compressImage({ img, type: file.fileType });
38
- const binaryString = atob(base64String.split('base64,')[1]);
39
- const uint8Array = Uint8Array.from(binaryString, (char) => char.charCodeAt(0));
40
- file.data = uint8Array.buffer;
41
-
42
- return FileModel.create(file);
43
- }
44
-
45
22
  async uploadImageByUrl(url: string, file: Pick<DB_File, 'name' | 'metadata'>) {
46
23
  const res = await fetch(API_ENDPOINTS.proxy, { body: url, method: 'POST' });
47
24
  const data = await res.arrayBuffer();
@@ -57,14 +34,6 @@ export class FileService {
57
34
  });
58
35
  }
59
36
 
60
- async removeFile(id: string) {
61
- return FileModel.delete(id);
62
- }
63
-
64
- async removeAllFiles() {
65
- return FileModel.clear();
66
- }
67
-
68
37
  async getFile(id: string): Promise<FilePreview> {
69
38
  const item = await FileModel.findById(id);
70
39
  if (!item) {
@@ -83,4 +52,37 @@ export class FileService {
83
52
  url,
84
53
  };
85
54
  }
55
+
56
+ async removeFile(id: string) {
57
+ return FileModel.delete(id);
58
+ }
59
+
60
+ async removeAllFiles() {
61
+ return FileModel.clear();
62
+ }
63
+
64
+ private isImage(fileType: string) {
65
+ const imageRegex = /^image\//;
66
+ return imageRegex.test(fileType);
67
+ }
68
+
69
+ private async uploadImageFile(file: DB_File) {
70
+ // 加载图片
71
+ const url = file.url || URL.createObjectURL(new Blob([file.data]));
72
+
73
+ const img = new Image();
74
+ img.src = url;
75
+ await (() =>
76
+ new Promise((resolve) => {
77
+ img.addEventListener('load', resolve);
78
+ }))();
79
+
80
+ // 压缩图片
81
+ const base64String = compressImage({ img, type: file.fileType });
82
+ const binaryString = atob(base64String.split('base64,')[1]);
83
+ const uint8Array = Uint8Array.from(binaryString, (char) => char.charCodeAt(0));
84
+ file.data = uint8Array.buffer;
85
+
86
+ return FileModel.create(file);
87
+ }
86
88
  }
@@ -1,3 +1,9 @@
1
- import { FileService } from './client';
1
+ // import { getClientConfig } from '@/config/client';
2
+ import { ClientService } from './client';
2
3
 
3
- export const fileService = new FileService();
4
+ // import { ServerService } from './server';
5
+ //
6
+ // const { ENABLED_SERVER_SERVICE } = getClientConfig();
7
+ //
8
+ // export const fileService = ENABLED_SERVER_SERVICE ? new ServerService() : new ClientService();
9
+ export const fileService = new ClientService();
@@ -0,0 +1,11 @@
1
+ /* eslint-disable typescript-sort-keys/interface */
2
+ import { DB_File } from '@/database/client/schemas/files';
3
+ import { FilePreview } from '@/types/files';
4
+
5
+ export interface IFileService {
6
+ uploadFile(file: DB_File): Promise<any>;
7
+ uploadImageByUrl(url: string, file: Pick<DB_File, 'name' | 'metadata'>): Promise<any>;
8
+ removeFile(id: string): Promise<any>;
9
+ removeAllFiles(): Promise<any>;
10
+ getFile(id: string): Promise<FilePreview>;
11
+ }
@@ -3,9 +3,9 @@ import { Mock, describe, expect, it, vi } from 'vitest';
3
3
  import { CreateMessageParams, MessageModel } from '@/database/client/models/message';
4
4
  import { ChatMessage, ChatMessageError, ChatPluginPayload } from '@/types/message';
5
5
 
6
- import { MessageService } from './client';
6
+ import { ClientService } from './client';
7
7
 
8
- const messageService = new MessageService();
8
+ const messageService = new ClientService();
9
9
 
10
10
  // Mock the MessageModel
11
11
  vi.mock('@/database/client/models/message', () => {
@@ -27,7 +27,7 @@ vi.mock('@/database/client/models/message', () => {
27
27
  };
28
28
  });
29
29
 
30
- describe('MessageService', () => {
30
+ describe('MessageClientService', () => {
31
31
  // Mock data
32
32
  const mockMessageId = 'mock-message-id';
33
33
  const mockMessage = {
@@ -57,7 +57,7 @@ describe('MessageService', () => {
57
57
  (MessageModel.create as Mock).mockResolvedValue({ id: mockMessageId });
58
58
 
59
59
  // Execute
60
- const messageId = await messageService.create(createParams);
60
+ const messageId = await messageService.createMessage(createParams);
61
61
 
62
62
  // Assert
63
63
  expect(MessageModel.create).toHaveBeenCalledWith(createParams);
@@ -71,7 +71,7 @@ describe('MessageService', () => {
71
71
  (MessageModel.batchCreate as Mock).mockResolvedValue(mockMessages);
72
72
 
73
73
  // Execute
74
- const result = await messageService.batchCreate(mockMessages);
74
+ const result = await messageService.batchCreateMessages(mockMessages);
75
75
 
76
76
  // Assert
77
77
  expect(MessageModel.batchCreate).toHaveBeenCalledWith(mockMessages);
@@ -79,32 +79,6 @@ describe('MessageService', () => {
79
79
  });
80
80
  });
81
81
 
82
- describe('hasMessages', () => {
83
- it('should return true if there are messages', async () => {
84
- // Setup
85
- (MessageModel.count as Mock).mockResolvedValue(1);
86
-
87
- // Execute
88
- const hasMessages = await messageService.hasMessages();
89
-
90
- // Assert
91
- expect(MessageModel.count).toHaveBeenCalled();
92
- expect(hasMessages).toBe(true);
93
- });
94
-
95
- it('should return false if there are no messages', async () => {
96
- // Setup
97
- (MessageModel.count as Mock).mockResolvedValue(0);
98
-
99
- // Execute
100
- const hasMessages = await messageService.hasMessages();
101
-
102
- // Assert
103
- expect(MessageModel.count).toHaveBeenCalled();
104
- expect(hasMessages).toBe(false);
105
- });
106
- });
107
-
108
82
  describe('removeMessage', () => {
109
83
  it('should remove a message by id', async () => {
110
84
  // Setup
@@ -172,7 +146,7 @@ describe('MessageService', () => {
172
146
  (MessageModel.clearTable as Mock).mockResolvedValue(true);
173
147
 
174
148
  // Execute
175
- const result = await messageService.clearAllMessage();
149
+ const result = await messageService.removeAllMessages();
176
150
 
177
151
  // Assert
178
152
  expect(MessageModel.clearTable).toHaveBeenCalled();