Last active
January 12, 2022 23:51
-
-
Save djdam/1dd3d0a1023a6533419aa4ec01ff7463 to your computer and use it in GitHub Desktop.
LocalForageStorage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import localforage from 'localforage'; | |
import { Auth } from 'aws-amplify'; | |
export class LocalForageStorage { | |
syncPromise = null; | |
memoryStore = {}; | |
asyncStore = localforage.createInstance({ | |
name: 'amplifyStore' | |
}); | |
setItem(key: string, value: any) { | |
this.asyncStore.setItem(key, value); | |
this.memoryStore[key] = value; | |
return this.memoryStore[key]; | |
} | |
getItem(key: string) { | |
return Object.prototype.hasOwnProperty.call(this.memoryStore, key) ? this.memoryStore[key] : undefined; | |
} | |
removeItem(key: string) { | |
this.asyncStore.removeItem(key); | |
return delete this.memoryStore[key]; | |
} | |
clear() { | |
this.asyncStore.clear(); | |
return {}; | |
} | |
sync(): Promise<void> { | |
if (!this.syncPromise) { | |
this.syncPromise = this.asyncStore.iterate((val: string, key) => { | |
this.memoryStore[key] = val; | |
}); | |
} | |
return this.syncPromise; | |
} | |
} | |
Auth.configure({ | |
storage: new LocalForageStorage() | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment