-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage.js
More file actions
116 lines (99 loc) · 2.42 KB
/
Copy pathstorage.js
File metadata and controls
116 lines (99 loc) · 2.42 KB
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
111
112
113
114
115
116
// ==========================================
// Persistent JSON Storage — survives restarts
// ==========================================
// Stores data as JSON files in the data/ directory.
// Provides a simple key-value interface with auto-save.
import fs from 'fs';
import path from 'path';
const DATA_DIR = path.resolve('data');
// Ensure data directory exists
if (!fs.existsSync(DATA_DIR)) {
fs.mkdirSync(DATA_DIR, { recursive: true });
}
export class JsonStore {
constructor(filename) {
this.filePath = path.join(DATA_DIR, filename);
this.data = this._load();
this._saveTimer = null;
this._writing = false;
this._pendingWrite = false;
}
_load() {
try {
if (fs.existsSync(this.filePath)) {
const raw = fs.readFileSync(this.filePath, 'utf8');
return JSON.parse(raw);
}
} catch (err) {
console.error(`[Storage] Failed to load ${this.filePath}:`, err.message);
}
return {};
}
_scheduleSave() {
// Debounce writes — flush at most every 2 seconds
if (this._saveTimer) return;
this._saveTimer = setTimeout(() => {
this._saveTimer = null;
this._flush();
}, 2000);
this._saveTimer.unref();
}
_flush() {
if (this._writing) {
this._pendingWrite = true;
return;
}
this._writing = true;
try {
const tmp = this.filePath + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(this.data, null, 2), 'utf8');
fs.renameSync(tmp, this.filePath);
} catch (err) {
console.error(`[Storage] Failed to save ${this.filePath}:`, err.message);
} finally {
this._writing = false;
if (this._pendingWrite) {
this._pendingWrite = false;
this._flush();
}
}
}
get(key) {
return this.data[key] ?? null;
}
set(key, value) {
this.data[key] = value;
this._scheduleSave();
}
delete(key) {
delete this.data[key];
this._scheduleSave();
}
has(key) {
return key in this.data;
}
keys() {
return Object.keys(this.data);
}
values() {
return Object.values(this.data);
}
entries() {
return Object.entries(this.data);
}
get size() {
return Object.keys(this.data).length;
}
clear() {
this.data = {};
this._scheduleSave();
}
/** Force an immediate write to disk */
saveNow() {
if (this._saveTimer) {
clearTimeout(this._saveTimer);
this._saveTimer = null;
}
this._flush();
}
}