All files / src/pages sitemap-posts.xml.ts

0% Statements 0/0
0% Branches 0/0
0% Functions 0/0
0% Lines 0/0

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34                                                                   
import { getCollection } from "astro:content";
import type { APIContext } from "astro";
import { SITE_URL, xmlEscape, formatDate } from "../utils/sitemap";
 
export async function GET(_context: APIContext) {
  const posts = await getCollection("blog");
 
  // 新しい順にソート
  const sorted = posts.sort(
    (a, b) => new Date(b.data.date).getTime() - new Date(a.data.date).getTime(),
  );
 
  const urlEntries = sorted
    .map((post) => {
      const lastmod = formatDate(post.data.date);
      return `  <url>
    <loc>${SITE_URL}/${xmlEscape(post.slug)}/</loc>
    <lastmod>${lastmod}</lastmod>
  </url>`;
    })
    .join("\n");
 
  const xml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${urlEntries}
</urlset>`;
 
  return new Response(xml, {
    headers: {
      "Content-Type": "application/xml; charset=utf-8",
    },
  });
}