ghost-keychain/packages/extension-base/src/stores/Base.ts
Jaco Greeff 837fb52a3a
Bumps w/ eslint (#338)
* Bumps w/ eslint

* Additional

* Additional

* Additional

* Additional

* Additional

* Linting done, tsc fixes remain

* Final round
2020-05-24 12:17:53 +02:00

67 lines
1.7 KiB
TypeScript

// Copyright 2019-2020 @polkadot/extension-base authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import chrome from '@polkadot/extension-inject/chrome';
type StoreValue = Record<string, unknown>;
const lastError = (type: string): void => {
const error = chrome.runtime.lastError;
if (error) {
console.error(`BaseStore.${type}:: runtime.lastError:`, error);
}
};
export default abstract class BaseStore <T> {
#prefix: string;
constructor (prefix: string | null) {
this.#prefix = prefix ? `${prefix}:` : '';
}
public all (update: (key: string, value: T) => void): void {
chrome.storage.local.get(null, (result: StoreValue): void => {
lastError('all');
Object
.entries(result)
.filter(([key]) => key.startsWith(this.#prefix))
.forEach(([key, value]): void => {
update(key.replace(this.#prefix, ''), value as T);
});
});
}
public get (_key: string, update: (value: T) => void): void {
const key = `${this.#prefix}${_key}`;
chrome.storage.local.get([key], (result: StoreValue): void => {
lastError('get');
update(result[key] as T);
});
}
public remove (_key: string, update?: () => void): void {
const key = `${this.#prefix}${_key}`;
chrome.storage.local.remove(key, (): void => {
lastError('remove');
update && update();
});
}
public set (_key: string, value: T, update?: () => void): void {
const key = `${this.#prefix}${_key}`;
chrome.storage.local.set({ [key]: value }, (): void => {
lastError('set');
update && update();
});
}
}