51 lines
1.1 KiB
JavaScript
51 lines
1.1 KiB
JavaScript
//@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;
|