From 40921a489269e84f6930eaab7df955c4afd5ce7f Mon Sep 17 00:00:00 2001 From: Joe Carstairs <65492573+Sycamost@users.noreply.github.com> Date: Fri, 25 Aug 2023 17:56:03 +0100 Subject: Adds an RSS feed with news items --- src/pages/[locale]/rss.xml.ts | 44 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/pages/[locale]/rss.xml.ts (limited to 'src/pages') diff --git a/src/pages/[locale]/rss.xml.ts b/src/pages/[locale]/rss.xml.ts new file mode 100644 index 0000000..be2cab6 --- /dev/null +++ b/src/pages/[locale]/rss.xml.ts @@ -0,0 +1,44 @@ +import rss, { RSSFeedItem } from '@astrojs/rss'; +import { CollectionEntry, getCollection } from 'astro:content'; +import { getDate, getHref, isNewsItemInLocale } from '$lib/newsUtils'; +import localeStaticPaths from '$lib/localeStaticPaths'; +import getLocaleFromPath from '$lib/getLocaleFromPath'; +import type { APIContext } from 'astro'; +import translate from '$i18n/translate'; +import tFeed from '$i18n/translations/pages/rss.xml'; + +export async function get(context: APIContext) { + const locale = getLocaleFromPath(context.url.pathname); + const t = translate(locale); + const news = (await getCollection('news')).filter((item) => isNewsItemInLocale(item, locale)); + const site = context.site; + if (!site) { + throw new Error('No site provided in Astro configuration'); + } + + return rss({ + title: t(tFeed, { key: 'title' }), + description: t(tFeed, { key: 'description' }), + site, + items: news.map(newsItemToRssFeedItem), + customData: `${locale}`, + }); +} + +function newsItemToRssFeedItem(item: CollectionEntry<'news'>): RSSFeedItem { + const pubDate = getDate(item); + if (!pubDate) { + throw new Error(`Could not determine publication date of ${item}`); + } + + return { + link: getHref(item), + title: item.data.title, + description: item.data.summary, + pubDate, + }; +} + +export async function getStaticPaths() { + return localeStaticPaths; +} -- cgit v1.2.3