generated from kevisual/vite-react-template
103 lines
2.7 KiB
TypeScript
103 lines
2.7 KiB
TypeScript
import { create } from 'zustand';
|
|
import { persist } from 'zustand/middleware';
|
|
import type { Config, defaultConfig } from './schema';
|
|
import { queryLogin } from '@/modules/query';
|
|
import { toast } from 'sonner';
|
|
|
|
type ConfigState = {
|
|
config: Config;
|
|
setConfig: (config: Partial<Config>) => void;
|
|
resetConfig: () => void;
|
|
saveToRemote: () => Promise<void>;
|
|
loadFromRemote: () => Promise<void>;
|
|
checkConfig: (opts?: { isUser?: boolean, reload?: boolean }) => Promise<boolean>;
|
|
};
|
|
|
|
const STORAGE_KEY = 'cnb-config';
|
|
|
|
const DEFAULT_CONFIG = {
|
|
CNB_API_KEY: '',
|
|
CNB_COOKIE: '',
|
|
CNB_CORS_URL: 'https://cors.kevisual.cn',
|
|
ENABLE_CORS: true,
|
|
AI_BASE_URL: 'https://api.cnb.cool/kevisual/cnb-ai/-/ai/',
|
|
AI_MODEL: 'CNB-Models',
|
|
AI_API_KEY: ''
|
|
}
|
|
const loadInitialConfig = (): Config => {
|
|
try {
|
|
const stored = localStorage.getItem(STORAGE_KEY);
|
|
if (stored) {
|
|
return JSON.parse(stored);
|
|
}
|
|
} catch {
|
|
// Ignore parse errors
|
|
}
|
|
return DEFAULT_CONFIG;
|
|
};
|
|
|
|
export const useConfigStore = create<ConfigState>()(
|
|
persist(
|
|
(set, get) => ({
|
|
config: loadInitialConfig(),
|
|
setConfig: (newConfig) =>
|
|
set((state) => ({
|
|
config: { ...state.config, ...newConfig },
|
|
})),
|
|
resetConfig: () =>
|
|
set({
|
|
config: DEFAULT_CONFIG,
|
|
}),
|
|
saveToRemote: async () => {
|
|
const _config = get().config;
|
|
const res = await queryLogin.post({
|
|
path: 'config',
|
|
key: 'update',
|
|
data: {
|
|
key: 'cnb_center_config.json',
|
|
data: _config,
|
|
}
|
|
});
|
|
if (res.code === 200) {
|
|
toast.success('保存到远端成功')
|
|
} else {
|
|
toast.error('保存到远端失败')
|
|
}
|
|
},
|
|
loadFromRemote: async () => {
|
|
const setConfig = (config: Config) => set({ config });
|
|
const res = await queryLogin.post({
|
|
path: 'config',
|
|
key: 'get',
|
|
data: {
|
|
key: 'cnb_center_config.json',
|
|
}
|
|
})
|
|
if (res.code === 404) {
|
|
toast.error('远端配置不存在')
|
|
return;
|
|
}
|
|
if (res.code === 200) {
|
|
const config = res.data?.data as typeof config;
|
|
setConfig(config);
|
|
toast.success('获取远端配置成功')
|
|
}
|
|
},
|
|
checkConfig: async (opts?: { isUser?: boolean, reload?: boolean }) => {
|
|
const { CNB_API_KEY } = get().config;
|
|
if (!CNB_API_KEY && opts?.isUser) {
|
|
await get().loadFromRemote();
|
|
if (opts?.reload) {
|
|
location.reload();
|
|
}
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
}),
|
|
{
|
|
name: STORAGE_KEY,
|
|
}
|
|
)
|
|
);
|