2021-01-14 18:07:05 +00:00
|
|
|
// Copyright 2020-2021 Signal Messenger, LLC
|
2020-10-30 20:34:04 +00:00
|
|
|
// SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2020-09-24 21:53:21 +00:00
|
|
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
2020-04-13 17:37:29 +00:00
|
|
|
import utils from './Helpers';
|
|
|
|
|
2021-04-02 20:28:07 +00:00
|
|
|
// Default implementation working with localStorage
|
2021-01-14 18:07:05 +00:00
|
|
|
const localStorageImpl: StorageInterface = {
|
2020-04-13 17:37:29 +00:00
|
|
|
put(key: string, value: any) {
|
|
|
|
if (value === undefined) {
|
|
|
|
throw new Error('Tried to store undefined');
|
|
|
|
}
|
|
|
|
localStorage.setItem(`${key}`, utils.jsonThing(value));
|
|
|
|
},
|
|
|
|
|
|
|
|
get(key: string, defaultValue: any) {
|
|
|
|
const value = localStorage.getItem(`${key}`);
|
|
|
|
if (value === null) {
|
|
|
|
return defaultValue;
|
|
|
|
}
|
|
|
|
return JSON.parse(value);
|
|
|
|
},
|
|
|
|
|
|
|
|
remove(key: string) {
|
|
|
|
localStorage.removeItem(`${key}`);
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
2021-01-14 18:07:05 +00:00
|
|
|
export type StorageInterface = {
|
2020-04-13 17:37:29 +00:00
|
|
|
put(key: string, value: any): void | Promise<void>;
|
|
|
|
get(key: string, defaultValue: any): any;
|
|
|
|
remove(key: string): void | Promise<void>;
|
2021-01-14 18:07:05 +00:00
|
|
|
};
|
2020-04-13 17:37:29 +00:00
|
|
|
|
|
|
|
const Storage = {
|
2021-01-14 18:07:05 +00:00
|
|
|
impl: localStorageImpl,
|
2020-04-13 17:37:29 +00:00
|
|
|
|
2020-09-24 21:53:21 +00:00
|
|
|
put(key: string, value: unknown): Promise<void> | void {
|
2020-04-13 17:37:29 +00:00
|
|
|
return Storage.impl.put(key, value);
|
|
|
|
},
|
|
|
|
|
2020-09-24 21:53:21 +00:00
|
|
|
get(key: string, defaultValue: unknown): Promise<unknown> {
|
2020-04-13 17:37:29 +00:00
|
|
|
return Storage.impl.get(key, defaultValue);
|
|
|
|
},
|
|
|
|
|
2020-09-24 21:53:21 +00:00
|
|
|
remove(key: string): Promise<void> | void {
|
2020-04-13 17:37:29 +00:00
|
|
|
return Storage.impl.remove(key);
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
|
|
|
export default Storage;
|