仓库
TIP
在一个群里有个同学说他去面试有个面试官问他如何设计一个仓库? 那咱们今天就设计一版。
设计
TIP
设计应该参考localstorage
, 具备getItem
、setItem
, removeItem
, clear
等基础api。
前端数据库indexDb
TIP
技术基于前端数据库indexDb
去实现封装,社区有个很好的localforage
npm 包实现的正好适合咱们的场景。
实现
TIP
基于localforage
的实现
TS
ts
import localforage from 'localforage';
interface BaseStorageProps {
getItem<T>(key: string): Promise<T | null>;
setItem<T>(key: string, value: T): Promise<T>;
removeItem(key: string): Promise<void>;
keys(): Promise<Array<string>>;
clear(): Promise<void>;
getInstance(name: string): BaseStorageProps;
}
class Storage implements BaseStorageProps {
private store: LocalForage;
constructor(name: string) {
this.store = localforage.createInstance({
name
});
}
public getItem<T>(key: string): Promise<T | null> {
return this.store.getItem(key);
}
public setItem<T>(key: string, value: T): Promise<T> {
return this.store.setItem(key, value);
}
public removeItem(key: string): Promise<void> {
return this.store.removeItem(key);
}
public keys(): Promise<string[]> {
return this.store.keys();
}
public clear(): Promise<void> {
return this.store.clear();
}
public getInstance(name: string): Storage {
return new Storage(name);
}
}
export { Storage };
export default new Storage('global-storage');
JS
js
import localforage from 'localforage';
class Storage {
#store = null;
constructor(name) {
this.#store = localforage.createInstance({ name });
}
getItem(key) {
return this.#store.getItem(key);
}
setItem(key, value) {
return this.#store.setItem(key, value);
}
removeItem(key) {
return this.#store.removeItem(key);
}
keys() {
return this.#store.keys();
}
clear() {
return this.#store.clear();
}
getInstance(name) {
return new Storage(name);
}
}
export { Storage };
export default new Storage('global-storage');