Browse Source

fix(@vben-core/preferences): avoid unscoped storage before init (#8329)

pull/8334/head
俞可 · YU KE 4 weeks ago
committed by GitHub
parent
commit
7ecacd6520
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 5
      .changeset/quiet-caches-wait.md
  2. 38
      packages/@core/preferences/__tests__/preferences.test.ts
  3. 4
      packages/@core/preferences/src/preferences.ts

5
.changeset/quiet-caches-wait.md

@ -0,0 +1,5 @@
---
'@vben-core/preferences': patch
---
fix(@vben-core/preferences): avoid unscoped localStorage before initialization

38
packages/@core/preferences/__tests__/preferences.test.ts

@ -61,6 +61,44 @@ describe('preferences', () => {
expect(preferences).toEqual(defaultPreferences);
});
it('uses memory storage until preferences are initialized', async () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
vi.useFakeTimers();
try {
const manager = new PreferenceManager();
manager.updatePreferences({ app: { locale: 'en-US' } });
await vi.advanceTimersByTimeAsync(151);
expect(localStorage.setItem).not.toHaveBeenCalled();
await manager.initPreferences({
namespace: 'testNamespace',
});
vi.mocked(localStorage.setItem).mockClear();
manager.updatePreferences({ app: { locale: 'en-US' } });
await vi.advanceTimersByTimeAsync(151);
expect(localStorage.setItem).toHaveBeenCalledWith(
'testNamespace-preferences',
expect.any(String),
);
expect(
vi
.mocked(localStorage.setItem)
.mock.calls.every(([key]) => key.startsWith('testNamespace-')),
).toBe(true);
expect(warnSpy).not.toHaveBeenCalledWith(
expect.stringContaining('empty prefix'),
);
} finally {
vi.clearAllTimers();
warnSpy.mockRestore();
vi.useRealTimers();
}
});
it('initializes preferences with overrides', async () => {
const overrides: any = {
app: {

4
packages/@core/preferences/src/preferences.ts

@ -10,7 +10,7 @@ import type {
import { markRaw, reactive, readonly, watch } from 'vue';
import { StorageManager } from '@vben-core/shared/cache';
import { MemoryStorageDriver, StorageManager } from '@vben-core/shared/cache';
import {
isMacOs,
merge,
@ -44,7 +44,7 @@ class PreferenceManager {
private state: Preferences;
constructor() {
this.cache = new StorageManager();
this.cache = new StorageManager({ driver: new MemoryStorageDriver() });
// 构造函数不再同步读取缓存,使用默认值初始化
// 真正的缓存加载在 initPreferences 中完成(已经是 async)
this.state = reactive<Preferences>({ ...defaultPreferences });

Loading…
Cancel
Save