[MIRROR] tgui: Add a proxy storage object with graceful fallback (#577)

* tgui: Add a proxy storage object with graceful fallback (#53294)

* tgui: Add a proxy storage object with graceful fallback

Co-authored-by: Aleksej Komarov <stylemistake@gmail.com>
This commit is contained in:
SkyratBot
2020-08-30 05:19:21 +02:00
committed by GitHub
co-authored by Aleksej Komarov
parent 455c0e8df4
commit 29a859ea79
3 changed files with 56 additions and 15 deletions
+52 -14
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 = {};
}
}
@@ -64,25 +64,24 @@ class MemoryBackend {
class LocalStorageBackend {
constructor() {
this.impl = IMPL_LOCAL_STORAGE;
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 +149,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
+3
View File
@@ -224,6 +224,9 @@ window.onerror = function (msg, url, line, col, error) {
return true;
};
// Catch unhandled rejections
window.onunhandledrejection = window.onerror;
// Helper for augmenting stack traces on fatal errors
window.__augmentStack__ = function (stack, error) {
return stack + '\nUser Agent: ' + navigator.userAgent;