Start building the post file service

This commit is contained in:
Dave Smith-Hayes 2024-07-09 21:33:27 -04:00
parent 5eb143ab4a
commit 87fd7b129b
2 changed files with 46 additions and 30 deletions

View File

@ -1,6 +1,6 @@
export type PostMeta = { export type PostMeta = {
title: string, title: string,
slug?: string, slug: string,
description?: string, description?: string,
html?: string, html?: string,
date: Date, date: Date,

View File

@ -4,33 +4,9 @@ import type { Post } from '@blog/models/Post';
import * as yamlFront from 'yaml-front-matter'; import * as yamlFront from 'yaml-front-matter';
import { marked } from 'marked'; import { marked } from 'marked';
export class PostFileService { export async function readPostFile(fileName: string): Promise<Post> {
private postFiles: string[];
private posts: Record<string, Post>;
public constructor(postFiles: string[]) {
this.postFiles = postFiles;
this.posts = new Record<string, Post>();
}
public static async create() {
const posts = new Record<string, Post>();
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<string> {
const file = Bun.file(POST_PATH + '/' + fileName); const file = Bun.file(POST_PATH + '/' + fileName);
return file.text(); const fileContent = await file.text();
}
protected async readPostFile(fileName: string): Promise<Post> {
const fileContent = await this.openFileAsText(fileName);
const parsedData = yamlFront.loadFront(fileContent); const parsedData = yamlFront.loadFront(fileContent);
const postHtml = await marked.parse(parsedData.__content); const postHtml = await marked.parse(parsedData.__content);
@ -47,4 +23,44 @@ export class PostFileService {
html: postHtml html: postHtml
}; };
} }
export class PostFileService {
private posts: Map<string, Post>;
public constructor(posts: Map<string, Post>) {
this.posts = posts;
}
public static async create() {
const posts = new Map<string, Post>();
const postFiles: string[] = await readdir(POST_PATH);
for (const postFile in postFiles) {
const post = await readPostFile(postFile);
const key = post.meta?.slug || postFile.slice(0, -3);
posts.set(key, post);
}
return new PostFileService(posts);
}
public getPostHtml(slug: string): string {
const html = this.posts.get(slug)?.html;
if (!html?.length) {
throw new Error("Post does not exist.");
}
return html;
}
public getPostRawContent(slug: string): string {
const content = this.posts.get(slug)?.content;
if (!content?.length) {
throw new Error("Post does not exist.");
}
return content;
}
} }