From ce8bb3e8f8c4d000663cd67b980f0b6de9c1a684 Mon Sep 17 00:00:00 2001 From: Vojtech Mares Date: Sun, 25 Jun 2023 15:59:34 +0200 Subject: [PATCH] feat: add static content utils, with gray-matter metadata --- lib/content/training.ts | 59 +++++++++++++++++++++++++++++++++++++++++ tsconfig.json | 3 ++- 2 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 lib/content/training.ts diff --git a/lib/content/training.ts b/lib/content/training.ts new file mode 100644 index 0000000..69ee391 --- /dev/null +++ b/lib/content/training.ts @@ -0,0 +1,59 @@ +import fs from 'fs'; +import path from 'path'; +import matter from 'gray-matter'; + +type Training = { + metadata: { + id: string; + name: string; + slug: string; + description: string; + days: number; + weight: number; + draft?: boolean; + logoURL?: string; + repositoryURL?: string; + priceOpen: number; + priceCorporate: number; + }; + + content: string; +}; + +export type { Training }; + +const root = process.cwd(); + +export async function getTrainingFiles() { + return fs.readdirSync(path.join(root, 'content', 'training'), 'utf-8'); +} + +export async function getTrainingBySlug(slug: string, fields: string[] = []) { + const source = fs.readFileSync(path.join(root, 'content', 'training', `${slug}.md`), 'utf8'); + + const { data, content } = matter(source); + + return { + metadata: data, + content: content, + }; +} + +export async function getAllTrainingsWithMetadata(): Promise { + const files = fs.readdirSync(path.join(root, 'content', 'training')) + + // @ts-ignore + return files.reduce((allTrainings, fileName) => { + const source = fs.readFileSync(path.join(root, 'content', 'training', fileName), 'utf8'); + const { data, content } = matter(source); + + return [ + { + metadata: data, + content: content, + }, + ...allTrainings, + ] + }, []) +} + diff --git a/tsconfig.json b/tsconfig.json index 03ebb74..04aeb35 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -18,7 +18,8 @@ "noUncheckedIndexedAccess": true, "baseUrl": ".", "paths": { - "~/*": ["./src/*"] + "~/*": ["./src/*"], + "~/lib/*": ["./lib/*"] } }, "include": [