Browse Source
- Make storage easier. (cherry picked from commit ed84a4732d7dd3ce6b2c22f30553ab5c59f85dbb)20230320
Jixun Wu
3 years ago
committed by
MengYX
8 changed files with 81 additions and 8 deletions
@ -1,7 +1,3 @@ |
|||||
import BaseStorage from './storage/BaseStorage'; |
import storageFactory from './storage/StorageFactory'; |
||||
import BrowserNativeStorage from './storage/BrowserNativeStorage'; |
|
||||
import ChromeExtensionStorage from './storage/ChromeExtensionStorage'; |
|
||||
|
|
||||
const storage: BaseStorage = ChromeExtensionStorage.works ? new ChromeExtensionStorage() : new BrowserNativeStorage(); |
export const storage = storageFactory(); |
||||
|
|
||||
export default storage; |
|
||||
|
@ -0,0 +1,32 @@ |
|||||
|
import BaseStorage from './BaseStorage'; |
||||
|
|
||||
|
export default class InMemoryStorage extends BaseStorage { |
||||
|
private values = new Map<string, any>(); |
||||
|
protected async load<T>(name: string, defaultValue: T): Promise<T> { |
||||
|
if (this.values.has(name)) { |
||||
|
return this.values.get(name); |
||||
|
} |
||||
|
|
||||
|
return defaultValue; |
||||
|
} |
||||
|
|
||||
|
protected async save<T>(name: string, value: T): Promise<void> { |
||||
|
this.values.set(name, value); |
||||
|
} |
||||
|
|
||||
|
public async getAll(): Promise<Record<string, any>> { |
||||
|
const result = {}; |
||||
|
this.values.forEach((value, key) => { |
||||
|
Object.assign(result, { |
||||
|
[key]: value, |
||||
|
}); |
||||
|
}); |
||||
|
return result; |
||||
|
} |
||||
|
|
||||
|
public async setAll(obj: Record<string, any>): Promise<void> { |
||||
|
for (const [key, value] of Object.entries(obj)) { |
||||
|
this.values.set(key, value); |
||||
|
} |
||||
|
} |
||||
|
} |
@ -0,0 +1,13 @@ |
|||||
|
import BaseStorage from './BaseStorage'; |
||||
|
import BrowserNativeStorage from './BrowserNativeStorage'; |
||||
|
import ChromeExtensionStorage from './ChromeExtensionStorage'; |
||||
|
import InMemoryStorage from './InMemoryStorage'; |
||||
|
|
||||
|
export default function storageFactory(): BaseStorage { |
||||
|
if (ChromeExtensionStorage.works) { |
||||
|
return new ChromeExtensionStorage(); |
||||
|
} else if (BrowserNativeStorage.works) { |
||||
|
return new BrowserNativeStorage(); |
||||
|
} |
||||
|
return new InMemoryStorage(); |
||||
|
} |
Loading…
Reference in new issue