diff --git a/packages/data-store-json/src/browser-local-storage-store.ts b/packages/data-store-json/src/browser-local-storage-store.ts new file mode 100644 index 000000000..29b428d7a --- /dev/null +++ b/packages/data-store-json/src/browser-local-storage-store.ts @@ -0,0 +1,89 @@ +import { IIdentifier, IMessage, ManagedKeyInfo } from '@veramo/core' +import { ManagedPrivateKey } from '@veramo/key-manager' +import { + DiffCallback, + VeramoJsonCache, + ClaimTableEntry, + CredentialTableEntry, + PresentationTableEntry, + VeramoJsonStore, +} from './types' + +/** + * Implementation of {@link VeramoJsonStore} that uses browser localStorage to store data + * + * @example + * ``` + * const dataStore = BrowserLocalStorageStore.fromLocalStorage('veramo-state') + * const plugin = new DataStoreJson(dataStore) + * ``` + */ +export class BrowserLocalStorageStore implements VeramoJsonStore { + notifyUpdate: DiffCallback + dids: Record + keys: Record + privateKeys: Record + credentials: Record + claims: Record + presentations: Record + messages: Record + + private constructor(private localStorageKey: string) { + this.notifyUpdate = async ( + oldState: VeramoJsonCache, + newState: VeramoJsonCache, + ) => { + this.save(newState) + } + this.dids = {} + this.keys = {} + this.privateKeys = {} + this.credentials = {} + this.claims = {} + this.presentations = {} + this.messages = {} + } + + public static fromLocalStorage(localStorageKey: string): BrowserLocalStorageStore { + const store = new BrowserLocalStorageStore(localStorageKey) + return store.load() + } + + private load(): BrowserLocalStorageStore { + if (typeof window !== 'undefined') { + const rawCache = window.localStorage.getItem(this.localStorageKey) || '{}' + let cache: VeramoJsonCache + try { + cache = JSON.parse(rawCache) + } catch (e: any) { + cache = {} + } + ({ + dids: this.dids, + keys: this.keys, + credentials: this.credentials, + claims: this.claims, + presentations: this.presentations, + messages: this.messages, + privateKeys: this.privateKeys, + } = { + dids: {}, + keys: {}, + credentials: {}, + claims: {}, + presentations: {}, + messages: {}, + privateKeys: {}, + ...cache, + }) + } + return this + } + + private save(newState: VeramoJsonCache): void { + if (typeof window !== 'undefined') { + window.localStorage.setItem(this.localStorageKey, JSON.stringify(newState)) + } + } + +} diff --git a/packages/data-store-json/src/index.ts b/packages/data-store-json/src/index.ts index 225693bae..f86435a66 100644 --- a/packages/data-store-json/src/index.ts +++ b/packages/data-store-json/src/index.ts @@ -21,3 +21,4 @@ export { export { DIDStoreJson } from './identifier/did-store' export { KeyStoreJson } from './identifier/key-store' export { PrivateKeyStoreJson } from './identifier/private-key-store' +export { BrowserLocalStorageStore } from './browser-local-storage-store'