refactor: update RSS feed generation

This commit is contained in:
radishzzz 2025-01-18 03:18:19 +00:00
parent 8c19d26cfd
commit 8a3e01fb96
4 changed files with 59 additions and 64 deletions

View file

@ -36,16 +36,12 @@ const { locale }: { locale: ThemeConfig['global']['locale'] } = themeConfig.glob
export default defineConfig({ export default defineConfig({
site: url, site: url,
base: '/', base: '/',
trailingSlash: 'always',
i18n: { i18n: {
locales: Object.entries(langMap).map(([path, codes]) => ({ locales: Object.entries(langMap).map(([path, codes]) => ({
path, path,
codes, codes,
})), })),
defaultLocale: locale, defaultLocale: locale,
routing: {
prefixDefaultLocale: false,
},
}, },
integrations: [ integrations: [
partytown({ partytown({

View file

@ -4,8 +4,6 @@ published: 1984-09-17
tags: ["黑泽明"] tags: ["黑泽明"]
--- ---
这里是文章内容...
一天,天色已晚。 仆人纪宁正在罗生门下等待雨停。 一天,天色已晚。 仆人纪宁正在罗生门下等待雨停。
除了他,宽大的门下空无一人。 只有一只蟋蟀栖息在一根大柱子上,柱子上有的地方已经脱漆。 罗生门位于铃作大寺街上,除了这个人之外,应该还有两三个人,包括避雨的一笠和搓着乌鸦帽的真江吉。 但是,除了这个人之外,一个人也没有。 除了他,宽大的门下空无一人。 只有一只蟋蟀栖息在一根大柱子上,柱子上有的地方已经脱漆。 罗生门位于铃作大寺街上,除了这个人之外,应该还有两三个人,包括避雨的一笠和搓着乌鸦帽的真江吉。 但是,除了这个人之外,一个人也没有。

View file

@ -8,23 +8,25 @@ import sanitizeHtml from 'sanitize-html'
const parser = new MarkdownIt() const parser = new MarkdownIt()
const { title, description, url } = themeConfig.site const { title, description, url } = themeConfig.site
const { locale: defaultLocale, moreLocale } = themeConfig.global const { moreLocale } = themeConfig.global
const followConfig = themeConfig.seo?.follow const followConfig = themeConfig.seo?.follow
// Extract first 100 chars from content as description // Returns first 200 chars with proper truncation
function getExcerpt(content: string): string { function getExcerpt(content: string): string {
const plainText = sanitizeHtml( if (!content)
parser.render(content), return ''
{
allowedTags: [],
allowedAttributes: {},
},
)
return `${plainText.slice(0, 100).trim()}...` // Convert markdown to plain text by removing all HTML tags
const plainText = sanitizeHtml(parser.render(content), {
allowedTags: [],
allowedAttributes: {},
})
const excerpt = plainText.slice(0, 200).trim()
return excerpt.length === 200 ? `${excerpt}...` : excerpt
} }
// Return 404 response for invalid language routes // Return 404 for invalid language paths
function return404() { function return404() {
return new Response(null, { return new Response(null, {
status: 404, status: 404,
@ -32,21 +34,22 @@ function return404() {
}) })
} }
// Add getStaticPaths for dynamic routes // Type for supported non-default languages
type SupportedLanguage = typeof moreLocale[number]
// Generate static paths for all supported languages
export function getStaticPaths() { export function getStaticPaths() {
return moreLocale.map(lang => ({ params: { lang } })) return moreLocale.map((lang: SupportedLanguage) => ({ params: { lang } }))
} }
// Generate RSS feed for non-default languages
export async function GET({ params }: APIContext) { export async function GET({ params }: APIContext) {
const lang = params.lang as string const lang = params.lang as SupportedLanguage
// Only generate RSS for valid non-default languages // Return 404 if language is not supported
if (!moreLocale.includes(lang)) { if (!moreLocale.includes(lang))
return return404() return return404()
}
// Get posts for specific language (include universal posts) // Get posts for specific language (including universal posts)
const posts = await getCollection( const posts = await getCollection(
'posts', 'posts',
({ data }: { data: CollectionEntry<'posts'>['data'] }) => ({ data }: { data: CollectionEntry<'posts'>['data'] }) =>
@ -57,28 +60,27 @@ export async function GET({ params }: APIContext) {
title: `${title} (${lang})`, title: `${title} (${lang})`,
description, description,
site: url, site: url,
stylesheet: '/rss/styles.xsl', items: posts.map((post: CollectionEntry<'posts'>) => ({
// Map posts to RSS items with language-specific URLs
items: posts.map(post => ({
title: post.data.title, title: post.data.title,
pubDate: post.data.published, pubDate: post.data.published,
description: post.data.description || getExcerpt(post.body), description: post.data.description || getExcerpt(post.body),
link: `/${lang}/posts/${post.slug}/`, // Generate absolute URL with language prefix
content: sanitizeHtml( link: new URL(`${lang}/posts/${post.slug}/`, url).toString(),
parser.render(post.body), // Convert markdown content to HTML, allowing img tags
{ content: post.body
allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img']), ? sanitizeHtml(parser.render(post.body), {
}, allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img']),
), })
: '',
})), })),
// Add language and follow challenge info // Add XML namespaces for language and follow challenge
customData: ` customData: `
<language>${lang}</language> <language>${lang}</language>
${followConfig?.feedID && followConfig?.userID ${followConfig?.feedID && followConfig?.userID
? `<follow_challenge> ? `<follow_challenge>
<feedId>${followConfig.feedID}</feedId> <feedId>${followConfig.feedID}</feedId>
<userId>${followConfig.userID}</userId> <userId>${followConfig.userID}</userId>
</follow_challenge>` </follow_challenge>`
: '' : ''
} }
`.trim(), `.trim(),

View file

@ -1,4 +1,3 @@
import type { APIContext } from 'astro'
import type { CollectionEntry } from 'astro:content' import type { CollectionEntry } from 'astro:content'
import themeConfig from '@/config' import themeConfig from '@/config'
import rss from '@astrojs/rss' import rss from '@astrojs/rss'
@ -11,22 +10,23 @@ const { title, description, url } = themeConfig.site
const { locale } = themeConfig.global const { locale } = themeConfig.global
const followConfig = themeConfig.seo?.follow const followConfig = themeConfig.seo?.follow
// Extract first 100 chars from content as description // Returns first 200 chars with proper truncation
function getExcerpt(content: string): string { function getExcerpt(content: string): string {
const plainText = sanitizeHtml( if (!content)
parser.render(content), return ''
{
allowedTags: [],
allowedAttributes: {},
},
)
return `${plainText.slice(0, 100).trim()}...` // Convert markdown to plain text by removing all HTML tags
const plainText = sanitizeHtml(parser.render(content), {
allowedTags: [],
allowedAttributes: {},
})
const excerpt = plainText.slice(0, 200).trim()
return excerpt.length === 200 ? `${excerpt}...` : excerpt
} }
// Generate RSS feed for default language
export async function GET() { export async function GET() {
// Only handle posts for default language // Get all posts for default language (including universal posts)
const posts = await getCollection( const posts = await getCollection(
'posts', 'posts',
({ data }: { data: CollectionEntry<'posts'>['data'] }) => ({ data }: { data: CollectionEntry<'posts'>['data'] }) =>
@ -37,28 +37,27 @@ export async function GET() {
title, title,
description, description,
site: url, site: url,
stylesheet: '/rss/styles.xsl',
// Map posts to RSS items
items: posts.map((post: CollectionEntry<'posts'>) => ({ items: posts.map((post: CollectionEntry<'posts'>) => ({
title: post.data.title, title: post.data.title,
pubDate: post.data.published, pubDate: post.data.published,
description: post.data.description || getExcerpt(post.body), description: post.data.description || getExcerpt(post.body),
link: `/posts/${post.slug}/`, // Generate absolute URL for post
content: sanitizeHtml( link: new URL(`posts/${post.slug}/`, url).toString(),
parser.render(post.body), // Convert markdown content to HTML, allowing img tags
{ content: post.body
allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img']), ? sanitizeHtml(parser.render(post.body), {
}, allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img']),
), })
: '',
})), })),
// Add language and follow challenge info // Add XML namespaces for language and follow challenge
customData: ` customData: `
<language>${locale}</language> <language>${locale}</language>
${followConfig?.feedID && followConfig?.userID ${followConfig?.feedID && followConfig?.userID
? `<follow_challenge> ? `<follow_challenge>
<feedId>${followConfig.feedID}</feedId> <feedId>${followConfig.feedID}</feedId>
<userId>${followConfig.userID}</userId> <userId>${followConfig.userID}</userId>
</follow_challenge>` </follow_challenge>`
: '' : ''
} }
`.trim(), `.trim(),