diff options
author | Ashelyn Rose <git@tempest.dev> | 2023-05-08 19:25:46 -0600 |
---|---|---|
committer | Ashelyn Rose <git@tempest.dev> | 2023-05-08 19:29:19 -0600 |
commit | d89d92d3936683f4212186cef517c7930dd5b33a (patch) | |
tree | cba24caddd1dc5f950b5e42eb333261f0c13dca5 /utils/post.ts | |
parent | 6cddfdf8fe9bccc291ee8625d42cb42fd4ce2134 (diff) |
add markdown rendering, copy in old posts
Diffstat (limited to 'utils/post.ts')
-rw-r--r-- | utils/post.ts | 56 |
1 files changed, 56 insertions, 0 deletions
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 = /^(?<date>[0-9]{4}-[0-9]{2}-[0-9]{2}(-[0-9]{1,2})?)_(?<slug>[^\.]+)\.md$/ + +export async function getPostSlugs(): Promise<string[]> { + 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<Post | null> { + 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 + } +} |