diff --git a/src/config.ts b/src/config.ts index 6063c27..9424dc1 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,2 +1,3 @@ export const POST_PATH: string = __dirname + '/../posts'; export const STATIC_PATH: string = __dirname + '/../static'; +export const POST_ROUTE_PREFIX: string = '/posts' diff --git a/src/models/Post.ts b/src/models/Post.ts index b373990..f86534c 100644 --- a/src/models/Post.ts +++ b/src/models/Post.ts @@ -1,4 +1,4 @@ -import { PostMeta } from '@blog/model/PostMeta'; +import { PostMeta } from '@blog/models/PostMeta'; export type Post = { meta: PostMeta, diff --git a/src/post/post-reader.ts b/src/post/post-reader.ts index 6fbcae2..042ed99 100644 --- a/src/post/post-reader.ts +++ b/src/post/post-reader.ts @@ -1,6 +1,6 @@ import { marked } from 'marked'; -import type { Post } from '@blog/model/Post'; -import type { PostMeta } from '@blog/model/PostMeta'; +import type { Post } from '@blog/models/Post'; +import type { PostMeta } from '@blog/models/PostMeta'; import * as yamlFront from 'yaml-front-matter'; import { readdir } from 'node:fs/promises'; diff --git a/src/services/post-file.ts b/src/services/post-file.ts index 174eabc..5a10df6 100644 --- a/src/services/post-file.ts +++ b/src/services/post-file.ts @@ -1,5 +1,50 @@ -import { POST_PATH } from '@blog/config'; +import { POST_PATH, POST_ROUTE_PREFIX } from '@blog/config'; +import { readdir } from 'node:fs/promises'; +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; + public constructor(postFiles: string[]) { + this.postFiles = postFiles; + this.posts = new Record(); + } + + public static async create() { + const posts = new Record(); + const postFiles: string[] = await readdir(POST_PATH); + for (const postFile in postFiles) { + const post = await this.readPostFile(postFile); + posts.add(postFile, post); + } + + return new PostFileService(postFiles); + } + + protected async openFileAsText(fileName: string): Promise { + const file = Bun.file(POST_PATH + '/' + fileName); + return file.text(); + } + + protected async readPostFile(fileName: string): Promise { + const fileContent = await this.openFileAsText(fileName); + const parsedData = yamlFront.loadFront(fileContent); + const postHtml = await marked.parse(parsedData.__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 + }; + } }