Blog/bun_plugins/onStartup-post-importer.ts

30 lines
1.1 KiB
TypeScript

import matter from 'gray-matter';
import { marked } from 'marked';
import { dbConnection } from "../src/db";
// When the server starts, import all the blog post metadata into the database
// Executed on startup because it's included in <root> ./bunfig.toml
// Only import if not running in production
(async () => {
if (process.env.NODE_ENV === 'production') return;
const glob = new Bun.Glob("**/*.md");
for await (const file of glob.scan("./content")) {
const {data, content } = matter(await Bun.file(`./content/${file}`).text());
const route = `/${file.replace(/\.md$/, "")}`;
// Remove the title from content if it matches the frontmatter title to avoid duplicate H1s
let processedContent = content;
if (data.title) {
const titleHeadingRegex = new RegExp(`^#\\s+${data.title.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*$`, 'm');
processedContent = content.replace(titleHeadingRegex, '').trim();
}
const bodyHtml = await marked.parse(processedContent);
dbConnection.addPost(route, data, bodyHtml);
}
console.log('Posts have been imported into db');
})();