import { getCollection } from "astro:content";
function formatPubDate(date) {
const timezone = process.env.PUBLIC_RSS_TIMEZONE
? process.env.PUBLIC_RSS_TIMEZONE
: import.meta.env.PUBLIC_RSS_TIMEZONE;
if (!timezone) {
return date;
}
try {
const year = date.getUTCFullYear();
const month = String(date.getUTCMonth() + 1).padStart(2, "0");
const day = String(date.getUTCDate()).padStart(2, "0");
const formatter = new Intl.DateTimeFormat("en-US", {
timeZone: timezone,
timeZoneName: "longOffset",
});
const parts = formatter.formatToParts(date);
const offsetPart = parts.find((p) => p.type === "timeZoneName");
const offset = offsetPart ? offsetPart.value.replace("GMT", "") : "+00:00";
const dateStr = `${year}-${month}-${day}T00:00:00${offset}`;
return new Date(dateStr);
} catch (e) {
console.warn(`Invalid timezone "${timezone}":`, e.message);
return date;
}
}
export async function GET(context) {
const posts = await getCollection("posts");
// Sort posts by date, newest first
posts.sort((a, b) => new Date(b.data.pubDate) - new Date(a.data.pubDate));
const siteUrl = context.site?.toString().replace(/\/$/, "") || "";
const items = posts
.map((post) => {
const title = post.data.title;
const description = post.data.description || "";
const link = `${siteUrl}/post/${post.id}/`;
const pubDate = formatPubDate(post.data.pubDate).toUTCString();
return ` -
${link}
${link}
${pubDate}
`;
})
.join("\n");
const rssXml = `
Atridad Lahiji
Recent posts from Atridad Lahiji
${siteUrl}/
en-us
${items}
`;
return new Response(rssXml, {
headers: {
"Content-Type": "application/xml",
},
});
}