refactor: storage factory + singleton
- Make storage easier. (cherry picked from commit ed84a4732d7dd3ce6b2c22f30553ab5c59f85dbb)remotes/origin/HEAD
parent
8673adfda6
commit
d8b362efbe
@ -1,7 +1,3 @@
|
||||
import BaseStorage from './storage/BaseStorage';
|
||||
import BrowserNativeStorage from './storage/BrowserNativeStorage';
|
||||
import ChromeExtensionStorage from './storage/ChromeExtensionStorage';
|
||||
import storageFactory from './storage/StorageFactory';
|
||||
|
||||
const storage: BaseStorage = ChromeExtensionStorage.works ? new ChromeExtensionStorage() : new BrowserNativeStorage();
|
||||
|
||||
export default storage;
|
||||
export const storage = storageFactory();
|
||||
|
@ -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