From 6769e18ffaff6342c6bafcdbda8e754d0110bd19 Mon Sep 17 00:00:00 2001 From: Ferdinand Thiessen Date: Fri, 26 Nov 2021 20:29:44 +0100 Subject: [PATCH] [api] Add PersistentStorage Wrapper for LocalStorage on browsers and Storage plugin on capacitor --- api/index.ts | 1 + api/src/utils/persistent.ts | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 api/src/utils/persistent.ts diff --git a/api/index.ts b/api/index.ts index a70c36a..183f34c 100644 --- a/api/index.ts +++ b/api/index.ts @@ -4,5 +4,6 @@ export * from './src/stores/'; export * from './src/utils/datetime'; export * from './src/utils/permission'; +export * from './src/utils/persistent'; export * from './src/utils/validators'; export * from './src/utils/misc'; diff --git a/api/src/utils/persistent.ts b/api/src/utils/persistent.ts new file mode 100644 index 0000000..9a5b58e --- /dev/null +++ b/api/src/utils/persistent.ts @@ -0,0 +1,35 @@ +import { LocalStorage, Platform } from 'quasar'; +import { Storage } from '@capacitor/storage'; + +type GetReturn = Date | number | boolean | string | object; + +export class PersistentStorage { + static clear() { + if (Platform.is.capacitor) return Storage.clear(); + else return Promise.resolve(LocalStorage.clear()); + } + + static remove(key: string) { + if (Platform.is.capacitor) return Storage.remove({ key: key }); + else return Promise.resolve(LocalStorage.remove(key)); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static set(key: string, value: any) { + if (Platform.is.capacitor) return Storage.set({ key, value: JSON.stringify(value) }); + else return Promise.resolve(LocalStorage.set(key, value)); + } + + static get(key: string) { + if (Platform.is.capacitor) + return Storage.get({ key }).then((v) => + v.value === null ? null : (JSON.parse(v.value) as T) + ); + else return Promise.resolve(LocalStorage.getItem(key)); + } + + static keys() { + if (Platform.is.capacitor) return Storage.keys().then((v) => v.keys); + else return Promise.resolve(LocalStorage.getAllKeys()); + } +}