Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
NebulaServices
GitHub Repository: NebulaServices/Nebula
Path: blob/main/src/utils/storage.ts
976 views
1
import { log } from "./index";
2
/**
3
* This class will create a new StoreManager with an appended prefix to it. The generic is there to tell you what that prefix ***is***
4
*
5
* **Note: there is already a defaultStore available! In most situations, you'll want to use that.**
6
*
7
* <code>
8
* const newStore = new StoreManager("incog");
9
*
10
* // Appends the prefix to the key passed. (EX: "incog||test")
11
* // Will return a string.
12
* newStore.getVal("test")
13
*
14
* // As stated above the prefix will automatically be appended to the key param (EX: "incog||test")
15
* newStore.setVal("test", "newVal");
16
* </code>
17
*/
18
class StoreManager<Prefix extends string /* This is here so I know what prefix is appended. It's inferred from the constructor */> {
19
#prefix: Prefix;
20
constructor(pref: Prefix) {
21
this.#prefix = pref;
22
}
23
getVal(key: string): string {
24
log({ type: 'info', bg: true, prefix: true }, `Getting key: ${key} \nFull key: ${this.#prefix}||${key}`);
25
return localStorage.getItem(`${this.#prefix}||${key}`) as string;
26
}
27
setVal(key: string, val: string): void {
28
log({ type: 'info', bg: false, prefix: true }, `Setting ${key} with value: ${val}`);
29
localStorage.setItem(`${this.#prefix}||${key}`, val);
30
}
31
removeVal(key: string): void {
32
log({ type: 'info', bg: true, prefix: true }, `Removing ${this.#prefix}||${key}`);
33
localStorage.removeItem(`${this.#prefix}||${key}`);
34
}
35
}
36
37
//this is done so I can see the prefix used.
38
const defaultStore = new StoreManager("nebula");
39
40
export { StoreManager, defaultStore };
41
42