|
| 1 | +import fs from 'node:fs/promises' |
| 2 | +import path from 'node:path' |
| 3 | +import { compileMdx } from 'nextra/compile' |
| 4 | +import { toString } from 'hast-util-to-string' |
| 5 | +import { type Root } from 'hast' |
| 6 | +import { type Plugin } from 'unified' |
| 7 | +import RSS from 'rss' |
| 8 | + |
| 9 | +const SITE_URL = 'https://kty.dev' |
| 10 | + |
| 11 | +const rehypeEnhanceFrontmatter: Plugin<[], Root> = () => (tree, file) => { |
| 12 | + const { frontMatter } = file.data as { |
| 13 | + frontMatter: Record<string, string | Date> |
| 14 | + } |
| 15 | + |
| 16 | + tree = { |
| 17 | + ...tree, |
| 18 | + children: tree.children.filter((node) => (node as any).tagName !== 'pre'), |
| 19 | + } |
| 20 | + |
| 21 | + const [filePath] = file.history |
| 22 | + |
| 23 | + frontMatter.description = toString(tree as any).trimStart() |
| 24 | + frontMatter.fileName = path.parse(filePath).name |
| 25 | + frontMatter.date = new Date(frontMatter.date) |
| 26 | +} |
| 27 | + |
| 28 | +export async function GET() { |
| 29 | + const files = await fs.readdir('./pages/blog') |
| 30 | + |
| 31 | + const blogs = await Promise.all( |
| 32 | + files |
| 33 | + .filter((filename) => /\.mdx?$/.test(filename)) |
| 34 | + .map(async (filename) => { |
| 35 | + const filePath = path.join('./pages/blog', filename) |
| 36 | + const content = await fs.readFile(filePath, 'utf8') |
| 37 | + return await compileMdx(content, { |
| 38 | + filePath, |
| 39 | + mdxOptions: { |
| 40 | + rehypePlugins: [rehypeEnhanceFrontmatter], |
| 41 | + }, |
| 42 | + }) |
| 43 | + }), |
| 44 | + ) |
| 45 | + |
| 46 | + blogs.sort((a, b) => b.frontMatter.date - a.frontMatter.date) |
| 47 | + |
| 48 | + const feed = new RSS({ |
| 49 | + title: 'Blog', |
| 50 | + description: 'Blog', |
| 51 | + feed_url: `${SITE_URL}/rss.xml`, |
| 52 | + site_url: SITE_URL, |
| 53 | + language: 'en-US', |
| 54 | + pubDate: blogs[0].frontMatter.date.toUTCString(), |
| 55 | + ttl: 60, |
| 56 | + }) |
| 57 | + |
| 58 | + for (const { frontMatter } of blogs) { |
| 59 | + feed.item({ |
| 60 | + title: frontMatter.title, |
| 61 | + description: frontMatter.description.slice(0, 139) + '…', |
| 62 | + url: `${SITE_URL}/blog/${frontMatter.fileName}`, |
| 63 | + author: frontMatter.byline, |
| 64 | + date: frontMatter.date.toUTCString(), |
| 65 | + }) |
| 66 | + } |
| 67 | + |
| 68 | + return new Response(feed.xml({ indent: true }), { |
| 69 | + headers: { |
| 70 | + 'Content-Type': 'application/xml; charset=utf-8', |
| 71 | + }, |
| 72 | + }) |
| 73 | +} |
0 commit comments