waffle/frontend/src/storage.js
2022-04-26 22:45:40 +03:00

53 lines
1.1 KiB
JavaScript

const defaults = {
apiBase: `${window.location.origin}/api/v1`,
gatewayBase: `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/gateway`
};
const dummyProvider = {
_store: {},
getItem(key) {
return this._store[key];
},
setItem(key, value) {
this._store[key] = value;
}
};
function getProvider() {
return window.localStorage || dummyProvider;
}
export function getItem(key) {
return getProvider().getItem(key);
}
export function setItem(key, value) {
return getProvider().setItem(key, value);
}
export function getAuthToken() {
return getItem("token");
}
export function setAuthToken(value) {
return setItem("token", value);
}
export function apiRoute(fragment) {
return `${getItem("apiBase")}/${fragment}`;
}
export function setItemIfNull(key, value) {
const provider = getProvider();
if (!provider.getItem(key)) {
provider.setItem(key, value);
return true;
}
return false;
}
export function initStorageDefaults() {
for (const [k, v] of Object.entries(defaults)) {
setItemIfNull(k, v);
}
}