|
| 1 | +import type { APIRoute } from "astro"; |
| 2 | +import { sanityFetch } from "@/utils/sanity"; |
| 3 | +import { sitemapQuery } from "@/lib/queries"; |
| 4 | + |
| 5 | +export const prerender = false; |
| 6 | + |
| 7 | +interface SitemapItem { |
| 8 | + _type: string; |
| 9 | + _updatedAt: string; |
| 10 | + slug: string; |
| 11 | +} |
| 12 | + |
| 13 | +function getPath(item: SitemapItem): string { |
| 14 | + if (item._type === "page") return `/${item.slug}`; |
| 15 | + return `/${item._type}/${item.slug}`; |
| 16 | +} |
| 17 | + |
| 18 | +export const GET: APIRoute = async () => { |
| 19 | + const site = "https://codingcat.dev"; |
| 20 | + const items = await sanityFetch<SitemapItem[]>(sitemapQuery); |
| 21 | + |
| 22 | + const staticPages = [ |
| 23 | + { url: site, lastmod: new Date().toISOString(), priority: "1.0" }, |
| 24 | + { url: `${site}/blog`, lastmod: new Date().toISOString(), priority: "0.8" }, |
| 25 | + { url: `${site}/podcasts`, lastmod: new Date().toISOString(), priority: "0.8" }, |
| 26 | + { url: `${site}/authors`, lastmod: new Date().toISOString(), priority: "0.5" }, |
| 27 | + { url: `${site}/guests`, lastmod: new Date().toISOString(), priority: "0.5" }, |
| 28 | + { url: `${site}/sponsors`, lastmod: new Date().toISOString(), priority: "0.5" }, |
| 29 | + ]; |
| 30 | + |
| 31 | + const dynamicPages = items.map((item) => ({ |
| 32 | + url: `${site}${getPath(item)}`, |
| 33 | + lastmod: item._updatedAt || new Date().toISOString(), |
| 34 | + priority: item._type === "post" || item._type === "podcast" ? "0.7" : "0.5", |
| 35 | + })); |
| 36 | + |
| 37 | + const allPages = [...staticPages, ...dynamicPages]; |
| 38 | + |
| 39 | + const xml = `<?xml version="1.0" encoding="UTF-8"?> |
| 40 | +<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> |
| 41 | +${allPages.map((p) => ` <url> |
| 42 | + <loc>${p.url}</loc> |
| 43 | + <lastmod>${p.lastmod}</lastmod> |
| 44 | + <priority>${p.priority}</priority> |
| 45 | + </url>`).join("\n")} |
| 46 | +</urlset>`; |
| 47 | + |
| 48 | + return new Response(xml, { |
| 49 | + headers: { |
| 50 | + "Content-Type": "application/xml", |
| 51 | + "Cache-Control": "public, max-age=3600", |
| 52 | + }, |
| 53 | + }); |
| 54 | +}; |
0 commit comments