47 lines
2.1 KiB
TypeScript
47 lines
2.1 KiB
TypeScript
import "server-only";
|
|
import { promises as fs } from "node:fs";
|
|
import path from "node:path";
|
|
import { cache } from "react";
|
|
import { initialContent, blankProject } from "./cms-defaults";
|
|
import type { CmsContent } from "./cms-types";
|
|
|
|
const filePath = path.join(process.cwd(), "data", "cms-content.json");
|
|
function mergeDefaults(base: unknown, value: unknown): unknown {
|
|
if (value === undefined) return base;
|
|
if (Array.isArray(base)) return value;
|
|
if (base && typeof base === "object" && value && typeof value === "object") {
|
|
return Object.fromEntries(Object.entries(base).map(([key, fallback]) => [key, mergeDefaults(fallback, (value as Record<string, unknown>)[key])]));
|
|
}
|
|
return value;
|
|
}
|
|
async function readContent(): Promise<CmsContent> {
|
|
try {
|
|
const raw = JSON.parse(await fs.readFile(filePath, "utf8"));
|
|
const merged = mergeDefaults(initialContent(), raw) as CmsContent;
|
|
merged.projects = merged.projects.map(project => ({ ...blankProject(), ...project }));
|
|
return merged;
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return initialContent();
|
|
throw error;
|
|
}
|
|
}
|
|
export const getCmsContent = cache(readContent);
|
|
export class ContentConflict extends Error {}
|
|
let pending: Promise<unknown> = Promise.resolve();
|
|
export function saveCmsContent(content: CmsContent): Promise<CmsContent> {
|
|
const save = pending.then(async () => {
|
|
const current = await readContent();
|
|
if (current.updatedAt !== content.updatedAt) throw new ContentConflict("تم تعديل المحتوى من جلسة أخرى. حمّل النسخة الأحدث قبل الحفظ.");
|
|
const clean = { ...content, updatedAt: new Date(Math.max(Date.now(), Date.parse(current.updatedAt) + 1)).toISOString() };
|
|
await fs.mkdir(path.dirname(filePath), { recursive: true });
|
|
const temporary = `${filePath}.${crypto.randomUUID()}.tmp`;
|
|
try {
|
|
await fs.writeFile(temporary, JSON.stringify(clean, null, 2), "utf8");
|
|
await fs.rename(temporary, filePath);
|
|
} finally { await fs.rm(temporary, { force: true }); }
|
|
return clean;
|
|
});
|
|
pending = save.catch(() => undefined);
|
|
return save;
|
|
}
|