webstorage moment

This commit is contained in:
Letter N
2020-08-30 09:39:07 +08:00
parent fe17bee28e
commit 8175486453
3 changed files with 55 additions and 14 deletions
+52 -13
View File
@@ -44,19 +44,19 @@ class MemoryBackend {
this.store = {};
}
async get(key) {
get(key) {
return this.store[key];
}
async set(key, value) {
set(key, value) {
this.store[key] = value;
}
async remove(key) {
remove(key) {
this.store[key] = undefined;
}
async clear() {
clear() {
this.store = {};
}
}
@@ -67,22 +67,22 @@ class LocalStorageBackend {
this.store = {};
}
async get(key) {
get(key) {
const value = localStorage.getItem(key);
if (typeof value === 'string') {
return JSON.parse(value);
}
}
async set(key, value) {
set(key, value) {
localStorage.setItem(key, JSON.stringify(value));
}
async remove(key) {
remove(key) {
localStorage.removeItem(key);
}
async clear() {
clear() {
localStorage.clear();
}
}
@@ -150,8 +150,47 @@ class IndexedDbBackend {
}
}
export const storage = (
testIndexedDb() && new IndexedDbBackend()
|| testLocalStorage() && new LocalStorageBackend()
|| new MemoryBackend()
);
/**
* Web Storage Proxy object, which selects the best backend available
* depending on the environment.
*/
class StorageProxy {
constructor() {
this.backendPromise = (async () => {
if (testIndexedDb()) {
try {
const backend = new IndexedDbBackend();
await backend.dbPromise;
return backend;
}
catch {}
}
if (testLocalStorage()) {
return new LocalStorageBackend();
}
return new MemoryBackend();
})();
}
async get(key) {
const backend = await this.backendPromise;
return backend.get(key);
}
async set(key, value) {
const backend = await this.backendPromise;
return backend.set(key, value);
}
async remove(key) {
const backend = await this.backendPromise;
return backend.remove(key);
}
async clear() {
const backend = await this.backendPromise;
return backend.clear();
}
}
export const storage = new StorageProxy();
File diff suppressed because one or more lines are too long
+2
View File
@@ -223,6 +223,8 @@ window.onerror = function (msg, url, line, col, error) {
// Prevent default action
return true;
};
// Catch unhandled rejections
window.onunhandledrejection = window.onerror;
// Helper for augmenting stack traces on fatal errors
window.__augmentStack__ = function (stack, error) {