diff --git a/src/models/PostMeta.ts b/src/models/PostMeta.ts index 60f2847..74cc179 100644 --- a/src/models/PostMeta.ts +++ b/src/models/PostMeta.ts @@ -1,6 +1,6 @@ export type PostMeta = { title: string, - slug?: string, + slug: string, description?: string, html?: string, date: Date, diff --git a/src/services/post-file.ts b/src/services/post-file.ts index 5a10df6..24f6212 100644 --- a/src/services/post-file.ts +++ b/src/services/post-file.ts @@ -4,47 +4,63 @@ import type { Post } from '@blog/models/Post'; import * as yamlFront from 'yaml-front-matter'; import { marked } from 'marked'; -export class PostFileService { - private postFiles: string[]; - private posts: Record; +export async function readPostFile(fileName: string): Promise { + const file = Bun.file(POST_PATH + '/' + fileName); + const fileContent = await file.text(); + const parsedData = yamlFront.loadFront(fileContent); + const postHtml = await marked.parse(parsedData.__content); - public constructor(postFiles: string[]) { - this.postFiles = postFiles; - this.posts = new Record(); + return { + meta: { + title: parsedData.title, + description: parsedData.description, + date: new Date(parsedData.date), + draft: parsedData?.draft || false, + tags: parsedData.tags, + slug: POST_ROUTE_PREFIX + '/' + fileName, + }, + content: parsedData.__content, + html: postHtml + }; +} + +export class PostFileService { + private posts: Map; + + public constructor(posts: Map) { + this.posts = posts; } public static async create() { - const posts = new Record(); + const posts = new Map(); const postFiles: string[] = await readdir(POST_PATH); + for (const postFile in postFiles) { - const post = await this.readPostFile(postFile); - posts.add(postFile, post); + const post = await readPostFile(postFile); + const key = post.meta?.slug || postFile.slice(0, -3); + posts.set(key, post); } - return new PostFileService(postFiles); + return new PostFileService(posts); } - protected async openFileAsText(fileName: string): Promise { - const file = Bun.file(POST_PATH + '/' + fileName); - return file.text(); + public getPostHtml(slug: string): string { + const html = this.posts.get(slug)?.html; + + if (!html?.length) { + throw new Error("Post does not exist."); + } + + return html; } - protected async readPostFile(fileName: string): Promise { - const fileContent = await this.openFileAsText(fileName); - const parsedData = yamlFront.loadFront(fileContent); - const postHtml = await marked.parse(parsedData.__content); + public getPostRawContent(slug: string): string { + const content = this.posts.get(slug)?.content; - return { - meta: { - title: parsedData.title, - description: parsedData.description, - date: new Date(parsedData.date), - draft: parsedData?.draft || false, - tags: parsedData.tags, - slug: POST_ROUTE_PREFIX + '/' + fileName, - }, - content: parsedData.__content, - html: postHtml - }; + if (!content?.length) { + throw new Error("Post does not exist."); + } + + return content; } }