2021-06-07 19:25:37 +02:00
|
|
|
import { StorageService } from "jslib-common/abstractions/storage.service";
|
2018-01-04 16:51:08 +01:00
|
|
|
|
2018-01-09 20:26:20 +01:00
|
|
|
export default class BrowserStorageService implements StorageService {
|
2018-01-12 06:06:53 +01:00
|
|
|
private chromeStorageApi: any;
|
2021-12-21 15:43:35 +01:00
|
|
|
|
2021-02-03 20:36:05 +01:00
|
|
|
constructor() {
|
|
|
|
this.chromeStorageApi = chrome.storage.local;
|
|
|
|
}
|
2021-12-21 15:43:35 +01:00
|
|
|
|
2021-06-15 20:40:49 +02:00
|
|
|
async get<T>(key: string): Promise<T> {
|
2021-04-23 10:45:20 +02:00
|
|
|
return new Promise((resolve) => {
|
2021-02-03 20:36:05 +01:00
|
|
|
this.chromeStorageApi.get(key, (obj: any) => {
|
|
|
|
if (obj != null && obj[key] != null) {
|
2021-01-13 16:43:18 +01:00
|
|
|
resolve(obj[key] as T);
|
2021-06-04 01:38:17 +02:00
|
|
|
return;
|
|
|
|
}
|
2021-02-03 20:36:05 +01:00
|
|
|
resolve(null);
|
2021-12-21 15:43:35 +01:00
|
|
|
});
|
2021-02-03 20:36:05 +01:00
|
|
|
});
|
2021-12-21 15:43:35 +01:00
|
|
|
}
|
|
|
|
|
2019-08-13 17:47:29 +02:00
|
|
|
async has(key: string): Promise<boolean> {
|
2021-02-03 20:36:05 +01:00
|
|
|
return (await this.get(key)) != null;
|
2021-12-21 15:43:35 +01:00
|
|
|
}
|
|
|
|
|
2021-02-03 20:36:05 +01:00
|
|
|
async save(key: string, obj: any): Promise<any> {
|
|
|
|
if (obj == null) {
|
|
|
|
// Fix safari not liking null in set
|
2021-04-23 10:45:20 +02:00
|
|
|
return new Promise<void>((resolve) => {
|
2021-02-03 20:36:05 +01:00
|
|
|
this.chromeStorageApi.remove(key, () => {
|
|
|
|
resolve();
|
|
|
|
});
|
2021-12-21 15:43:35 +01:00
|
|
|
});
|
2018-01-04 16:51:08 +01:00
|
|
|
}
|
|
|
|
|
2019-08-13 17:47:29 +02:00
|
|
|
if (obj instanceof Set) {
|
2021-02-03 20:36:05 +01:00
|
|
|
obj = Array.from(obj);
|
2018-01-04 16:51:08 +01:00
|
|
|
}
|
2021-12-21 15:43:35 +01:00
|
|
|
|
2021-02-03 20:36:05 +01:00
|
|
|
const keyedObj = { [key]: obj };
|
2021-04-23 10:45:20 +02:00
|
|
|
return new Promise<void>((resolve) => {
|
2021-02-03 20:36:05 +01:00
|
|
|
this.chromeStorageApi.set(keyedObj, () => {
|
|
|
|
resolve();
|
2021-12-21 15:43:35 +01:00
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2019-08-13 17:47:29 +02:00
|
|
|
async remove(key: string): Promise<any> {
|
2021-04-23 10:45:20 +02:00
|
|
|
return new Promise<void>((resolve) => {
|
2021-02-03 20:36:05 +01:00
|
|
|
this.chromeStorageApi.remove(key, () => {
|
|
|
|
resolve();
|
2021-12-21 15:43:35 +01:00
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
2018-01-04 16:51:08 +01:00
|
|
|
}
|