-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathlocalstorage.js
110 lines (94 loc) · 2.54 KB
/
localstorage.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import path from 'path';
import fs from 'fs';
import os from 'os';
import { LowSync } from 'lowdb';
import { JSONFileSync } from 'lowdb/node';
let db;
// Construct the path to the data file
const homeDir = os.homedir();
const launcherDir = path.join(homeDir, '.jsgamelauncher');
// Initialize and use your database
async function initializeDB(gameFolder) {
// Ensure the launcher directory exists
if (!fs.existsSync(launcherDir)) {
fs.mkdirSync(launcherDir, { recursive: true });
}
const gameDir = path.join(launcherDir, gameFolder);
// Ensure the game data directory exists
if (!fs.existsSync(gameDir)) {
fs.mkdirSync(gameDir, { recursive: true });
}
const dataFile = path.join(gameDir, 'data.json');
console.log('Using data file:', dataFile);
// Use JSON file for storage
db = new LowSync(new JSONFileSync(dataFile), {});
db.read();
console.log('DB data:', db.data);
db.data = db.data || {}; // Set default data if it's empty
return {
db,
dataFile,
};
}
export default async function createLocalStorage(gameFolder) {
const initObj = await initializeDB(gameFolder);
const ls = {
__storageFile: initObj.dataFile,
setItem: (key, value) => {
console.log('called setItem', key, value);
db.data[key] = String(value); // Set a value
db.write(); // Write the data back to the file
},
getItem: (key) => {
return db.data[key] || null;
},
removeItem: (key) => {
delete db.data[key];
db.write();
},
clear: () => {
const keys = Object.keys(db.data);
for (const key of keys) {
delete db.data[key];
}
db.write();
},
key: (index) => {
const keys = Object.keys(db.data);
return keys[index] || null; // Return null if index is out of bounds
},
};
Object.defineProperties(ls, {
length: {
get() {
return Object.keys(db.data).length;
},
configurable: true,
enumerable: true,
},
});
return new Proxy(ls, {
get: (target, prop) => {
if (prop in target) {
return target[prop];
} else if (prop in db.data) {
return db.data[prop];
} else {
return undefined;
}
},
set: (target, prop, value) => {
db.data[prop] = String(value); // Set a value
db.write(); // Write the data back to the file
return true;
},
deleteProperty: (target, prop) => {
if (prop in target.storage) {
delete db.data[key];
db.write();
return true;
}
return false;
},
});
}