()
| 15 | |
| 16 | // 异步加载配置并应用 |
| 17 | async function loadConfig() { |
| 18 | try { |
| 19 | const value = await storage.getItem('local:config'); |
| 20 | if (typeof value === 'string' && value.trim().length > 0) { |
| 21 | const parsedConfig = JSON.parse(value); |
| 22 | if (isConfigObjectValid(parsedConfig)) { |
| 23 | // 如果配置有效,合并到当前 config 中 |
| 24 | Object.assign(config, parsedConfig); |
| 25 | return; // 加载成功,直接返回 |
| 26 | } |
| 27 | } |
| 28 | // 如果存储中没有配置、配置为空或无效,则将当前带有默认值的 config 对象存入存储 |
| 29 | await storage.setItem('local:config', JSON.stringify(config)); |
| 30 | } catch (error) { |
| 31 | console.error('Error loading or validating config:', error); |
| 32 | // 出错时也尝试保存一次默认配置 |
| 33 | try { |
| 34 | await storage.setItem('local:config', JSON.stringify(new Config())); |
| 35 | } catch (saveError) { |
| 36 | console.error('Failed to save default config after an error:', saveError); |
| 37 | } |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | // 监控配置变化并更新 config |
| 42 | storage.watch('local:config', (newValue: any, oldValue: any) => { |
no test coverage detected