add local storage in json for collection

This commit is contained in:
2025-08-17 12:58:16 +01:00
parent 0260afb152
commit 0b6c687f7f
4 changed files with 116 additions and 11 deletions

View File

@@ -0,0 +1,45 @@
import { NextRequest } from 'next/server';
import { promises as fs } from 'fs';
import path from 'path';
const DATA_DIR = path.join(process.cwd(), 'data');
const FILE_PATH = path.join(DATA_DIR, 'checklist.json');
async function ensureFile(): Promise<void> {
try {
await fs.mkdir(DATA_DIR, { recursive: true });
} catch {}
try {
await fs.access(FILE_PATH);
} catch {
// create empty object file on first use
await fs.writeFile(FILE_PATH, JSON.stringify({}, null, 2), 'utf-8');
}
}
export async function GET() {
try {
await ensureFile();
const raw = await fs.readFile(FILE_PATH, 'utf-8');
const data = raw ? JSON.parse(raw) : {};
return Response.json({ data }, { status: 200 });
} catch (err) {
console.error('GET /api/checklist error', err);
return Response.json({ data: {} }, { status: 200 });
}
}
export async function PUT(req: NextRequest) {
try {
const body = await req.json();
if (typeof body !== 'object' || body === null || Array.isArray(body)) {
return Response.json({ error: 'Invalid payload' }, { status: 400 });
}
await ensureFile();
await fs.writeFile(FILE_PATH, JSON.stringify(body, null, 2), 'utf-8');
return Response.json({ ok: true }, { status: 200 });
} catch (err) {
console.error('PUT /api/checklist error', err);
return Response.json({ error: 'Write failed' }, { status: 500 });
}
}

View File

@@ -1,7 +1,7 @@
"use client";
import React, { useEffect, useMemo, useState } from 'react';
import type { TcgCard } from '@/types/pokemon';
import { loadChecklist, saveChecklist } from '@/lib/checklist';
import { loadChecklistServer, saveChecklistServer } from '@/lib/checklist';
import type { ChecklistV2, VariantKey } from '@/lib/checklist';
import CardGrid from '@/components/CardGrid';
import Header from '@/components/Header';
@@ -18,7 +18,10 @@ export default function Page() {
const [tab, setTab] = useState<'uncollected' | 'collected'>('uncollected');
useEffect(() => {
setChecklist(loadChecklist());
(async () => {
const data = await loadChecklistServer();
setChecklist(data);
})();
}, []);
useEffect(() => {
@@ -48,7 +51,8 @@ export default function Page() {
// Clean up empty records to keep storage tidy
const hasAny = Object.values(current).some(Boolean);
if (hasAny) next[id] = current; else delete next[id];
saveChecklist(next);
// fire-and-forget save to server; fallback handled in lib
void saveChecklistServer(next);
return next;
});
}