Branchwell

Become a Pro / website · becomeapro.ai / src / lib / lessons.ts

Raw 2.1 KB on 0104128d30a01b5156cca2446fd234b2f1fa3673
1import fs from "fs";
2import path from "path";
3import matter from "gray-matter";
4import { AREAS } from "@/lib/catalog";
5import type { LessonMeta } from "@/lib/lesson-types";
6
7export * from "@/lib/lesson-types";
8
9export type Lesson = LessonMeta & { body: string };
10
11const CONTENT_DIR = path.join(process.cwd(), "content", "lessons");
12
13// gray-matter parses unquoted YAML dates into Date objects
14function isoDay(value: unknown): string {
15 return value instanceof Date ? value.toISOString().slice(0, 10) : String(value ?? "").slice(0, 10);
16}
17
18function readLesson(area: string, field: string, file: string): Lesson {
19 const raw = fs.readFileSync(path.join(CONTENT_DIR, area, field, file), "utf8");
20 const { data, content } = matter(raw);
21 const where = `${area}/${field}/${file}`;
22 if (!data.title || !data.description || !data.updated) {
23 throw new Error(`Lesson ${where} needs a title, description and updated date`);
24 }
25 return {
26 area,
27 field,
28 slug: file.replace(/\.mdx$/, ""),
29 title: data.title,
30 description: data.description,
31 level: data.level ?? "Beginner",
32 minutes: data.minutes ?? 10,
33 updated: isoDay(data.updated),
34 order: typeof data.order === "number" ? data.order : 99,
35 body: content,
36 };
37}
38
39let cache: Lesson[] | null = null;
40
41export function getAllLessons(): Lesson[] {
42 if (cache) return cache;
43 cache = AREAS.flatMap((area) =>
44 area.fields.flatMap((field) => {
45 const dir = path.join(CONTENT_DIR, area.slug, field.slug);
46 if (!fs.existsSync(dir)) return [];
47 return fs
48 .readdirSync(dir)
49 .filter((f) => f.endsWith(".mdx"))
50 .map((f) => readLesson(area.slug, field.slug, f));
51 })
52 ).sort((a, b) => a.order - b.order || a.title.localeCompare(b.title));
53 return cache;
54}
55
56export function getLessonMetas(): LessonMeta[] {
57 return getAllLessons().map(({ body, ...meta }) => meta);
58}
59
60export function getFieldLessons(field: string): LessonMeta[] {
61 return getLessonMetas().filter((l) => l.field === field);
62}
63
64export function getLesson(area: string, field: string, slug: string): Lesson | undefined {
65 return getAllLessons().find((l) => l.area === area && l.field === field && l.slug === slug);
66}