waffle/frontend/src/storage.js

60 lines
1.7 KiB
JavaScript
Raw Normal View History

const defaults = {
2022-08-05 22:29:20 +03:00
"server:apiBase": `${window.location.origin || ""}/api/v1`,
"server:gatewayBase": `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/gateway`,
"auth:token": "",
"ui:doAnimations": true,
"ui:theme": "dark",
"state:openChannelId": -1,
"log:Gateway": false,
"log:Store": false,
2022-08-04 02:17:23 +03:00
"ui:stateful:presistSelectedChannel": true,
"ui:showSidebarToggle": false
};
2022-05-05 16:31:10 +03:00
const store = new Map(Object.entries(defaults));
const persistentProvider = localStorage;
2022-05-06 01:55:21 +03:00
let didCacheProvider = false;
2022-05-05 16:31:10 +03:00
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) {
2022-05-06 01:55:21 +03:00
if (!didCacheProvider) {
init();
}
2022-05-05 16:31:10 +03:00
return store.get(key);
}
2022-05-05 16:31:10 +03:00
export function removeItem(key) {
store.delete(key);
if (persistentProvider) {
persistentProvider.removeItem(key);
}
}
2022-05-05 16:31:10 +03:00
export function init() {
if (!persistentProvider)
return;
2022-05-05 16:31:10 +03:00
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);
2022-05-05 16:31:10 +03:00
}
}
});
2022-05-06 01:55:21 +03:00
didCacheProvider = true;
}
export function apiRoute(fragment) {
return `${getItem("server:apiBase")}/${fragment}`
}