store.js
1.32 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
// Generic JSON-file CRUD store (dev-plan.md T1), shared by characters.json/
// garments.json/dance-refs.json. Same full-read/full-write pattern as
// server.js's library.json — no in-memory cache, so a process restart just
// re-reads the file.
const fs = require("fs");
const crypto = require("crypto");
function createStore(filePath) {
function all() {
try {
return JSON.parse(fs.readFileSync(filePath, "utf8"));
} catch {
return [];
}
}
function save(items) {
fs.writeFileSync(filePath, JSON.stringify(items, null, 2));
}
return {
list() {
return all();
},
get(id) {
return all().find((item) => item.id === id) || null;
},
create(data) {
const items = all();
const item = { id: crypto.randomUUID(), createdAt: Date.now(), ...data };
items.push(item);
save(items);
return item;
},
update(id, patch) {
const items = all();
const idx = items.findIndex((item) => item.id === id);
if (idx === -1) return null;
items[idx] = { ...items[idx], ...patch, id };
save(items);
return items[idx];
},
remove(id) {
const items = all();
const next = items.filter((item) => item.id !== id);
save(next);
return next.length !== items.length;
},
};
}
module.exports = { createStore };