jadefin/JadefinStorage.js

51 lines
1.1 KiB
JavaScript
Raw Normal View History

2024-03-01 21:01:22 +01:00
//@ts-check
import JadefinIntegrity from "./JadefinIntegrity.js";
class JadefinStorage {
getKey;
cache = [];
/**
* @param {(name: string) => string} getKey
*/
constructor(getKey) {
this.getKey = getKey;
}
/**
* @param {string} name
* @param {any} [fallback]
*/
get(name, fallback) {
let value = this.cache[name];
if (value != null && value != undefined) {
return value;
}
value = localStorage.getItem(this.getKey(name));
if (value != null && value != undefined) {
try {
return this.cache[name] = JSON.parse(value);
} catch {
}
}
return this.cache[name] = fallback;
}
/**
* @param {string} name
* @param {any} value
*/
set(name, value) {
localStorage.setItem(this.getKey(name), JSON.stringify(this.cache[name] = value));
}
}
// @ts-ignore
JadefinStorage = JadefinIntegrity("JadefinStorage", import.meta.url, () => JadefinStorage);
export default JadefinStorage;