This commit is contained in:
61
src/routes/sitemap.xml/+server.ts
Normal file
61
src/routes/sitemap.xml/+server.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { db } from '$lib/server/db';
|
||||
import { blogArticles } from '$lib/server/db/schema';
|
||||
import { SITE_ORIGIN } from '$lib/seo';
|
||||
import { races } from '$lib/derby/races';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import type { RequestHandler } from './$types';
|
||||
|
||||
const staticPaths = [
|
||||
'/',
|
||||
'/projects',
|
||||
'/blog',
|
||||
'/lists',
|
||||
'/projects/catch-em-all',
|
||||
'/projects/animaldex',
|
||||
'/projects/derby',
|
||||
'/projects/spotify-beatmap-finder'
|
||||
];
|
||||
|
||||
function escapeXml(value: string): string {
|
||||
return value.replace(/[<>&"']/g, (character) => {
|
||||
const entities: Record<string, string> = {
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'&': '&',
|
||||
'"': '"',
|
||||
"'": '''
|
||||
};
|
||||
return entities[character];
|
||||
});
|
||||
}
|
||||
|
||||
export const GET: RequestHandler = async () => {
|
||||
const [articles, lists] = await Promise.all([
|
||||
db
|
||||
.select({ slug: blogArticles.slug, updatedAt: blogArticles.updatedAt })
|
||||
.from(blogArticles)
|
||||
.where(eq(blogArticles.status, 'published')),
|
||||
db.query.lists.findMany({ columns: { slug: true } })
|
||||
]);
|
||||
const entries: { path: string; lastmod?: string }[] = [
|
||||
...staticPaths.map((path) => ({ path })),
|
||||
...races.map((race) => ({ path: `/projects/derby/${race.slug}` })),
|
||||
...articles.map((article) => ({
|
||||
path: `/blog/${encodeURIComponent(article.slug)}`,
|
||||
lastmod: article.updatedAt.toISOString()
|
||||
})),
|
||||
...lists.map((list) => ({ path: `/lists/${encodeURIComponent(list.slug)}` }))
|
||||
];
|
||||
const body = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${entries
|
||||
.map(
|
||||
({ path, lastmod }) =>
|
||||
` <url><loc>${escapeXml(new URL(path, SITE_ORIGIN).href)}</loc>${lastmod ? `<lastmod>${lastmod}</lastmod>` : ''}</url>`
|
||||
)
|
||||
.join('\n')}\n</urlset>\n`;
|
||||
return new Response(body, {
|
||||
headers: {
|
||||
'content-type': 'application/xml; charset=utf-8',
|
||||
'cache-control': 'public, max-age=3600'
|
||||
}
|
||||
});
|
||||
};
|
||||
Reference in New Issue
Block a user