store.js 1.32 KB
// 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 };