feat: add RSS feed generation and content management features

This commit is contained in:
radishzzz 2025-01-14 09:10:12 +00:00
parent 4d989e0a7d
commit 5d3a3b0321
6 changed files with 189 additions and 49 deletions

View file

@ -1,33 +1,62 @@
import type { APIContext } from 'astro'
import type { CollectionEntry } from 'astro:content'
import themeConfig from '@/config'
import rss from '@astrojs/rss'
import { getCollection } from 'astro:content'
import MarkdownIt from 'markdown-it'
import sanitizeHtml from 'sanitize-html'
import
const parser = new MarkdownIt()
const { title, description, url } = themeConfig.site
const { language } = themeConfig.global
const followConfig = themeConfig.seo?.follow
// Extract first 100 chars from content as description
function getExcerpt(content: string): string {
const plainText = sanitizeHtml(
parser.render(content),
{
allowedTags: [],
allowedAttributes: {},
},
)
return `${plainText.slice(0, 100).trim()}...`
}
// Generate RSS feed
export async function GET(_context: APIContext) {
const posts = await getCollection('blog', ({ data }) => {
return !data.draft // 只包含非草稿文章
})
const posts = await getCollection(
'posts',
({ data }: { data: CollectionEntry<'posts'>['data'] }) => !data.draft,
)
return rss({
title,
description,
site: url,
items: posts.map(post => ({
stylesheet: '/rss/styles.xsl',
items: posts.map((post: CollectionEntry<'posts'>) => ({
title: post.data.title,
pubDate: post.data.published, // 使用 published 而不是 pubDate
description: post.data.description,
pubDate: post.data.published,
description: post.data.description || getExcerpt(post.body),
link: `/posts/${post.slug}/`,
content: sanitizeHtml(parser.render(post.body), {
allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img']),
}),
content: sanitizeHtml(
parser.render(post.body),
{
allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img']),
},
),
})),
customData: `<language>${language}</language>`,
customData: `
<language>${language}</language>
${followConfig?.feedID && followConfig?.userID
? `<follow_challenge>
<feedId>${followConfig.feedID}</feedId>
<userId>${followConfig.userID}</userId>
</follow_challenge>`
: ''
}
`.trim(),
})
}