generated from kevisual/vite-react-template
feat: 添加远端配置保存与加载功能,优化配置检查逻辑
This commit is contained in:
@@ -1,10 +1,15 @@
|
||||
import { create } from 'zustand';
|
||||
import type { GiteaConfig } from './schema';
|
||||
import { queryLogin } from '@/modules/query';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
type GiteaConfigState = {
|
||||
config: GiteaConfig;
|
||||
setConfig: (config: Partial<GiteaConfig>) => void;
|
||||
resetConfig: () => void;
|
||||
saveToRemote: () => Promise<void>;
|
||||
loadFromRemote: () => Promise<void>;
|
||||
checkConfig: (opts?: { isUser?: boolean, reload?: boolean }) => Promise<boolean>;
|
||||
};
|
||||
|
||||
const DEFAULT_CONFIG: GiteaConfig = {
|
||||
@@ -35,7 +40,7 @@ const saveConfig = (config: GiteaConfig) => {
|
||||
}
|
||||
};
|
||||
|
||||
export const useGiteaConfigStore = create<GiteaConfigState>()((set) => ({
|
||||
export const useGiteaConfigStore = create<GiteaConfigState>()((set, get) => ({
|
||||
config: loadInitialConfig(),
|
||||
setConfig: (newConfig) =>
|
||||
set((state) => {
|
||||
@@ -47,4 +52,50 @@ export const useGiteaConfigStore = create<GiteaConfigState>()((set) => ({
|
||||
saveConfig(DEFAULT_CONFIG);
|
||||
return set({ config: DEFAULT_CONFIG });
|
||||
},
|
||||
saveToRemote: async () => {
|
||||
const _config = get().config;
|
||||
const res = await queryLogin.post({
|
||||
path: 'config',
|
||||
key: 'update',
|
||||
data: {
|
||||
key: 'gitea_config.json',
|
||||
data: _config,
|
||||
}
|
||||
});
|
||||
if (res.code === 200) {
|
||||
toast.success('保存到远端成功')
|
||||
} else {
|
||||
toast.error('保存到远端失败')
|
||||
}
|
||||
},
|
||||
loadFromRemote: async () => {
|
||||
const setConfig = (config: GiteaConfig) => set({ config });
|
||||
const res = await queryLogin.post({
|
||||
path: 'config',
|
||||
key: 'get',
|
||||
data: {
|
||||
key: 'gitea_config.json',
|
||||
}
|
||||
})
|
||||
if (res.code === 404) {
|
||||
toast.error('远端配置不存在')
|
||||
return;
|
||||
}
|
||||
if (res.code === 200) {
|
||||
const config = res.data?.data as GiteaConfig;
|
||||
setConfig(config);
|
||||
toast.success('获取远端配置成功')
|
||||
}
|
||||
},
|
||||
checkConfig: async (opts?: { isUser?: boolean, reload?: boolean }) => {
|
||||
const { GITEA_TOKEN } = get().config;
|
||||
if (!GITEA_TOKEN && opts?.isUser) {
|
||||
await get().loadFromRemote();
|
||||
if (opts?.reload) {
|
||||
location.reload();
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}));
|
||||
|
||||
Reference in New Issue
Block a user