fix: 修复关键逻辑错误

- 修复 store 初始化的异步问题:构造函数中的异步方法现在正确等待
- 修复配置切换时删除原文件的严重 bug:使用 copyFile 替代 rename 避免文件丢失
- 简化代码实现,移除过度设计的部分
This commit is contained in:
Jason
2025-08-10 20:36:17 +08:00
parent 5f0ef8a441
commit 9dac53b754
3 changed files with 23 additions and 26 deletions

View File

@@ -7,11 +7,13 @@ export class SimpleStore {
private configPath: string
private configDir: string
private data: AppConfig = { providers: {}, current: '' }
private initPromise: Promise<void>
constructor() {
this.configDir = path.join(os.homedir(), '.cc-switch')
this.configPath = path.join(this.configDir, 'config.json')
this.loadData()
// 立即开始加载,但不阻塞构造函数
this.initPromise = this.loadData()
}
private async loadData(): Promise<void> {
@@ -36,12 +38,14 @@ export class SimpleStore {
}
}
get<T>(key: keyof AppConfig, defaultValue?: T): T {
async get<T>(key: keyof AppConfig, defaultValue?: T): Promise<T> {
await this.initPromise // 等待初始化完成
const value = this.data[key] as T
return value !== undefined ? value : (defaultValue as T)
}
async set<K extends keyof AppConfig>(key: K, value: AppConfig[K]): Promise<void> {
await this.initPromise // 等待初始化完成
this.data[key] = value
await this.saveData()
}