capybara/frontend/storage.js
2022-08-26 22:09:08 +03:00

47 lines
1.4 KiB
JavaScript

const defaults = {
"server:gatewayBase": `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/gateway`,
"auth:token": "",
};
const store = new Map(Object.entries(defaults));
const persistentProvider = localStorage;
let didCacheProvider = false;
export function setItem(key, value) {
store.set(key, value);
if (persistentProvider) {
persistentProvider.setItem(key, typeof value === "string" ? value : JSON.stringify(value));
}
}
export function getItem(key) {
if (!didCacheProvider) {
init();
}
return store.get(key);
}
export function removeItem(key) {
store.delete(key);
if (persistentProvider) {
persistentProvider.removeItem(key);
}
}
export function init() {
if (!persistentProvider)
return;
store.forEach((defaultValue, key) => {
const override = persistentProvider.getItem(key);
if (override !== null) {
try {
store.set(key, typeof defaultValue === "string" ? override : JSON.parse(override));
} catch (o_O) {
console.warn("[Storage]", `init(): An exception was thrown while parsing the value of key "${key}" from persistentProvider. The key "${key}" will be removed from persistentProvider.`, o_O);
persistentProvider.removeItem(key);
}
}
});
didCacheProvider = true;
}