ReactでRSSを作る
2023/9/25 0:33:00
import { Post } from "@/models";
import React from "react";
import { renderToString } from 'react-dom/server';
declare global {
namespace JSX {
interface IntrinsicElements {
[elemName: string]: unknown;
}
}
}
export function RssFeed({ posts }: { posts: Post[] }) {
return renderToString(
<rss version='2.0'>
<channel>
<language>ja</language>
<title>t_wの輪郭</title>
<rsslink>https://towasys.com/</rsslink>
<description>t_wの輪郭のRSSです。</description>
{posts.map(post => <item>
<title>{(post.title ? post.title : "あれ") + "|" + post.kno}</title>
<description>{post.body_html ?? ""}</description>
{post.posted_at && <pubDate>{new Date(post.posted_at * 1000).toUTCString()}</pubDate>}
<rsslink>{`https://towasys.com/${post.kno}`}</rsslink>
<guid isPermaLink="true">{`https://towasys.com/${post.kno}`}</guid>
</item>)}
</channel>
</rss>
).replaceAll("rsslink", "link")
}
Next.jsでの使い方
getServerSidePropsで下記を実行
const rss_feed = RssFeed({ posts })
context.res.statusCode = 200
context.res.setHeader('Cache-Control', 's-maxage=86400, stale-while-revalidate') // 24時間キャッシュする
context.res.setHeader('Content-Type', 'text/xml')
context.res.end(rss_feed)
return {
props: {},
}