Become a Pro / website · becomeapro.ai / src / lib / lessons.ts
| 1 | import fs from "fs"; |
| 2 | import path from "path"; |
| 3 | import matter from "gray-matter"; |
| 4 | import { AREAS } from "@/lib/catalog"; |
| 5 | import type { LessonMeta } from "@/lib/lesson-types"; |
| 6 | |
| 7 | export * from "@/lib/lesson-types"; |
| 8 | |
| 9 | export type Lesson = LessonMeta & { body: string }; |
| 10 | |
| 11 | const CONTENT_DIR = path.join(process.cwd(), "content", "lessons"); |
| 12 | |
| 13 | // gray-matter parses unquoted YAML dates into Date objects |
| 14 | function isoDay(value: unknown): string { |
| 15 | return value instanceof Date ? value.toISOString().slice(0, 10) : String(value ?? "").slice(0, 10); |
| 16 | } |
| 17 | |
| 18 | function 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 | |
| 39 | let cache: Lesson[] | null = null; |
| 40 | |
| 41 | export 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 | |
| 56 | export function getLessonMetas(): LessonMeta[] { |
| 57 | return getAllLessons().map(({ body, ...meta }) => meta); |
| 58 | } |
| 59 | |
| 60 | export function getFieldLessons(field: string): LessonMeta[] { |
| 61 | return getLessonMetas().filter((l) => l.field === field); |
| 62 | } |
| 63 | |
| 64 | export 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 | } |