import { queryCollection } from '@nuxt/content/server'
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig()
const siteUrl = config.public.siteUrl || 'https://example.com'
const locale = 'en'
// In Nitro server routes, `queryCollection` expects the H3 event as the first argument.
const allPosts = await queryCollection(event, 'blog').all()
const posts = allPosts
.filter((post: any) => post.path?.startsWith('/en/blog/') && post.draft !== true)
.sort((a: any, b: any) => new Date(b.date).getTime() - new Date(a.date).getTime())
const escapeXml = (str: string) => {
return str
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
}
const rssItems = posts
.map((post) => {
const routePath = post.path?.replace(/^\/en/, '') || ''
const link = `${siteUrl}${routePath}`
const pubDate = new Date(post.date).toUTCString()
return `
-
${escapeXml(post.title)}
${escapeXml(link)}
${escapeXml(link)}
${pubDate}
${escapeXml(post.description || '')}
`
})
.join('')
const rss = `
Blog - ${escapeXml(config.public.siteName || 'My Site')}
${siteUrl}/blog
Latest blog posts
${locale}
${rssItems}
`
event.node.res.setHeader('Content-Type', 'application/rss+xml; charset=utf-8')
return rss
})