From d89d92d3936683f4212186cef517c7930dd5b33a Mon Sep 17 00:00:00 2001 From: Ashelyn Rose Date: Mon, 8 May 2023 19:25:46 -0600 Subject: add markdown rendering, copy in old posts --- utils/post.ts | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 utils/post.ts (limited to 'utils') diff --git a/utils/post.ts b/utils/post.ts new file mode 100644 index 0000000..b2dd328 --- /dev/null +++ b/utils/post.ts @@ -0,0 +1,56 @@ +import { promises as fs } from 'fs' +import path from 'path' + +import frontmatter from 'front-matter' + +export interface Post { + slug: string, + date: Date, + title: string, + subtitle?: string, + author: string, + body: string +} + +const POST_FILE_PATTERN = /^(?[0-9]{4}-[0-9]{2}-[0-9]{2}(-[0-9]{1,2})?)_(?[^\.]+)\.md$/ + +export async function getPostSlugs(): Promise { + const postsDir = path.join(process.cwd(), 'posts') + const postPaths = await fs.readdir(postsDir) + return postPaths.map(getSlugFromFilePath).filter(slug => slug !== null) +} + +export function getSlugFromFilePath(postPath: string): string | null { + const regexResult = POST_FILE_PATTERN.exec(postPath) + if (!regexResult) return null + return regexResult.groups.slug +} + +export async function loadSinglePage(slug: string): Promise { + const postsDir = path.join(process.cwd(), 'posts') + const postPaths = await fs.readdir(postsDir) + const postMatch: RegExpExecArray | null = postPaths + .map((postFile: string) => POST_FILE_PATTERN.exec(postFile)) + .filter((regexResult: RegExpExecArray | null) => regexResult !== null) + .find((regexResult: RegExpExecArray) => regexResult.groups.slug === slug) + + if (!postMatch) return null; + + const fileName = `${postMatch.groups.date}_${postMatch.groups.slug}.md` + const fileContents = (await fs.readFile(path.join(process.cwd(), 'posts', fileName))).toString('utf8') + const { attributes, body } = frontmatter(fileContents) + + type Attributes = { [key: string]: string } + const data: Attributes = attributes as Attributes + + if (!data.title) return null; + + return { + slug: postMatch.groups.slug, + date: new Date(postMatch.groups.date), + title: data.title, + subtitle: data.subtitle, + author: data.author, + body + } +} -- cgit 1.4.1