42 lines
1.5 KiB
TypeScript
42 lines
1.5 KiB
TypeScript
import { createError, defineEventHandler, readBody } from "h3";
|
|
|
|
import { requireAdmin } from "@/lib/admin-auth.server";
|
|
import { readContent, sanitizeCinemas, writeContent } from "@/lib/content.server";
|
|
|
|
/**
|
|
* วาง JSON ของโรงหนัง (ออบเจกต์เดียวหรือ array) เพื่อเพิ่ม/ทับรายการเดิม
|
|
* ใช้กับปุ่ม "วาง JSON" ในหน้า admin — ทับเฉพาะ slug ที่ซ้ำกัน
|
|
*/
|
|
export default defineEventHandler(async (event) => {
|
|
requireAdmin(event);
|
|
const body = (await readBody(event)) as { raw?: string };
|
|
const raw = (body?.raw ?? "").trim();
|
|
if (!raw) {
|
|
throw createError({ statusCode: 400, statusMessage: "ยังไม่มีข้อมูลให้วาง" });
|
|
}
|
|
|
|
let parsed: unknown;
|
|
try {
|
|
parsed = JSON.parse(raw);
|
|
} catch (error) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage: `JSON ไม่ถูกต้อง: ${error instanceof Error ? error.message : ""}`,
|
|
});
|
|
}
|
|
|
|
const incoming = sanitizeCinemas(Array.isArray(parsed) ? parsed : [parsed]);
|
|
const current = await readContent();
|
|
|
|
const bySlug = new Map(current.cinemas.map((cinema) => [cinema.slug, cinema]));
|
|
for (const cinema of incoming) bySlug.set(cinema.slug, cinema);
|
|
|
|
const next = {
|
|
cinemas: Array.from(bySlug.values()),
|
|
site: current.site,
|
|
about: current.about,
|
|
};
|
|
await writeContent(next);
|
|
return { imported: incoming.length, store: next };
|
|
});
|