Add the Post service code.

This commit is contained in:
Dave Smith-Hayes 2024-07-08 22:12:48 -04:00
parent db3e79fd8f
commit 5eb143ab4a
4 changed files with 50 additions and 4 deletions

View File

@ -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'

View File

@ -1,4 +1,4 @@
import { PostMeta } from '@blog/model/PostMeta';
import { PostMeta } from '@blog/models/PostMeta';
export type Post = {
meta: PostMeta,

View File

@ -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';

View File

@ -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<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);
return file.text();
}
protected async readPostFile(fileName: string): Promise<Post> {
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
};
}
}