Przymiarka do dokumentów

This commit is contained in:
dm
2025-12-13 13:37:27 +01:00
parent 53ef126303
commit 9caf91fbfb
7 changed files with 260 additions and 15 deletions

77
src/lib/documents.ts Normal file
View File

@@ -0,0 +1,77 @@
import fs from "node:fs";
import path from "node:path";
import yaml from "js-yaml";
export type DocYaml = {
title: string;
visible?: boolean;
intro?: string;
content: string; // markdown
};
export type DocEntry = DocYaml & {
slug: string;
file: string;
};
const DOCS_DIR = path.join(process.cwd(), "src", "content", "document");
export function listDocuments(): DocEntry[] {
if (!fs.existsSync(DOCS_DIR)) return [];
const files = fs
.readdirSync(DOCS_DIR)
.filter((f) => /\.ya?ml$/i.test(f));
const items: DocEntry[] = [];
for (const file of files) {
const full = path.join(DOCS_DIR, file);
const raw = fs.readFileSync(full, "utf8");
const data = (yaml.load(raw) ?? {}) as Partial<DocYaml>;
const slug = file.replace(/\.ya?ml$/i, "");
// minimalna walidacja, żeby nic nie wybuchało
if (!data.title || typeof data.title !== "string") continue;
if (!data.content || typeof data.content !== "string") continue;
items.push({
slug,
file,
title: data.title,
visible: data.visible ?? false,
intro: data.intro ?? "",
content: data.content,
});
}
return items;
}
export function getDocumentBySlug(slug: string): DocEntry | null {
// akceptuj .yaml i .yml
const candidates = [`${slug}.yaml`, `${slug}.yml`];
for (const file of candidates) {
const full = path.join(DOCS_DIR, file);
if (!fs.existsSync(full)) continue;
const raw = fs.readFileSync(full, "utf8");
const data = (yaml.load(raw) ?? {}) as Partial<DocYaml>;
if (!data.title || typeof data.title !== "string") return null;
if (!data.content || typeof data.content !== "string") return null;
return {
slug,
file,
title: data.title,
visible: data.visible ?? false,
intro: data.intro ?? "",
content: data.content,
};
}
return null;
}