forked from lobehub/lobe-chat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.ts
109 lines (92 loc) · 2.69 KB
/
config.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import { notification } from '@/components/AntdStaticMethods';
import { BRANDING_NAME } from '@/const/branding';
import { CURRENT_CONFIG_VERSION, Migration } from '@/migrations';
import {
ConfigFile,
ConfigFileAgents,
ConfigFileAll,
ConfigFileSessions,
ConfigFileSettings,
ConfigFileSingleSession,
ConfigModelMap,
ExportType,
} from '@/types/exportConfig';
export const exportConfigFile = (config: object, fileName?: string) => {
const file = `${BRANDING_NAME}-${fileName || '-config'}-v${CURRENT_CONFIG_VERSION}.json`;
// 创建一个 Blob 对象
const blob = new Blob([JSON.stringify(config)], { type: 'application/json' });
// 创建一个 URL 对象,用于下载
const url = URL.createObjectURL(blob);
// 创建一个 <a> 元素,设置下载链接和文件名
const a = document.createElement('a');
a.href = url;
a.download = file;
// 触发 <a> 元素的点击事件,开始下载
document.body.append(a);
a.click();
// 下载完成后,清除 URL 对象
URL.revokeObjectURL(url);
a.remove();
};
export const importConfigFile = async (
file: File,
onConfigImport: (config: ConfigFile) => Promise<void>,
) => {
const text = await file.text();
try {
const config = JSON.parse(text);
const { state, version } = Migration.migrate(config);
await onConfigImport({ ...config, state, version });
} catch (error) {
console.error(error);
notification.error({
description: `出错原因: ${(error as Error).message}`,
message: '导入失败',
});
}
};
type CreateConfigFileState<T extends ExportType> = ConfigModelMap[T]['state'];
type CreateConfigFile<T extends ExportType> = ConfigModelMap[T]['file'];
export const createConfigFile = <T extends ExportType>(
type: T,
state: CreateConfigFileState<T>,
): CreateConfigFile<T> => {
switch (type) {
case 'agents': {
return {
exportType: 'agents',
state,
version: Migration.targetVersion,
} as ConfigFileAgents;
}
case 'sessions': {
return {
exportType: 'sessions',
state,
version: Migration.targetVersion,
} as ConfigFileSessions;
}
case 'settings': {
return {
exportType: 'settings',
state,
version: Migration.targetVersion,
} as ConfigFileSettings;
}
case 'singleSession': {
return {
exportType: 'sessions',
state,
version: Migration.targetVersion,
} as ConfigFileSingleSession;
}
case 'all': {
return {
exportType: 'all',
state,
version: Migration.targetVersion,
} as ConfigFileAll;
}
}
throw new Error('缺少正确的导出类型,请检查实现...');
};