feat: 动态sitemap.xml
This commit is contained in:
35
src/pages/sitemap-posts.xml.ts
Normal file
35
src/pages/sitemap-posts.xml.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import type {APIRoute} from 'astro';
|
||||
import {metadata} from "@/consts";
|
||||
import {createHttp} from "@/lib/request.ts";
|
||||
import type {PostForSitemap} from "@/types";
|
||||
import dayjs from "dayjs";
|
||||
|
||||
const site = metadata.site
|
||||
|
||||
export const GET: APIRoute = async (context) => {
|
||||
const http = createHttp(context.request.headers);
|
||||
|
||||
const {data} = await http.get<ApiResponse<PostForSitemap[]>>("posts/sitemap")
|
||||
|
||||
const urls = data
|
||||
.filter((url, index, array) => {
|
||||
return array.indexOf(url) === index;
|
||||
});
|
||||
|
||||
const xml = `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||
${urls.map((post) => `<url>
|
||||
<loc>${site}/${post.slug}</loc>
|
||||
<lastmod>${dayjs(post.updated_at || post.created_at).toISOString()}</lastmod>
|
||||
</url>`
|
||||
)
|
||||
.join('\n')}
|
||||
</urlset>`;
|
||||
|
||||
return new Response(xml, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'application/xml; charset=utf-8',
|
||||
'Cache-Control': 'public, max-age=3600, s-maxage=3600',
|
||||
},
|
||||
});
|
||||
};
|
||||
Reference in New Issue
Block a user