Start building the post file service
This commit is contained in:
parent
5eb143ab4a
commit
87fd7b129b
@ -1,6 +1,6 @@
|
||||
export type PostMeta = {
|
||||
title: string,
|
||||
slug?: string,
|
||||
slug: string,
|
||||
description?: string,
|
||||
html?: string,
|
||||
date: Date,
|
||||
|
@ -4,33 +4,9 @@ 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> {
|
||||
export async function readPostFile(fileName: string): Promise<Post> {
|
||||
const file = Bun.file(POST_PATH + '/' + fileName);
|
||||
return file.text();
|
||||
}
|
||||
|
||||
protected async readPostFile(fileName: string): Promise<Post> {
|
||||
const fileContent = await this.openFileAsText(fileName);
|
||||
const fileContent = await file.text();
|
||||
const parsedData = yamlFront.loadFront(fileContent);
|
||||
const postHtml = await marked.parse(parsedData.__content);
|
||||
|
||||
@ -46,5 +22,45 @@ export class PostFileService {
|
||||
content: parsedData.__content,
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user