MCPcopy Create free account
hub / github.com/Moddable-OpenSource/moddable / Preference

Class Preference

modules/files/preference/lin/preference.js:4–65  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

2import config from "mc/config";
3
4export default class Preference {
5 static #filePath = config.file.root + "modpreferences.json";
6 static #cache = Preference.#load();
7
8 static set(domain, key, value) {
9 if (value instanceof ArrayBuffer)
10 value = {buffer: (new Uint8Array(value).toString())};
11
12 Preference.#cache[domain] ??= {};
13 Preference.#cache[domain][key] = value;
14 Preference.#save();
15 }
16
17 static get(domain, key) {
18 let result = Preference.#cache[domain]?.[key];
19
20 if (result && ("object" === typeof result))
21 result = Uint8Array.from(result.buffer.split(",")).buffer;
22
23 return result;
24 }
25
26 static delete(domain, key) {
27 if (Preference.#cache[domain]?.[key] !== undefined) {
28 delete Preference.#cache[domain][key];
29 if (Object.keys(Preference.#cache[domain]).length === 0)
30 delete Preference.#cache[domain];
31 Preference.#save();
32 }
33 }
34
35 static keys(domain) {
36 return Preference.#cache[domain] ? Object.keys(Preference.#cache[domain]) : [];
37 }
38
39 static #load() {
40 let result = {};
41
42 try {
43 if (File.exists(Preference.#filePath)) {
44 let file = new File(Preference.#filePath, false);
45 result = JSON.parse(file.read(String));
46 file.close();
47 }
48 } catch {
49 // ignore errors
50 }
51
52 return result;
53 }
54
55 static #save() {
56 try {
57 File.delete(Preference.#filePath);
58 const file = new File(Preference.#filePath, true);
59 file.write(JSON.stringify(Preference.#cache));
60 file.close();
61 } catch {

Callers

nothing calls this directly

Calls 1

#loadMethod · 0.80

Tested by

no test coverage detected