|
| 1 | +import { website } from '$/lib/assets/config/website'; |
| 2 | +import { extractCategories } from '$/lib/server/posts/lib/categories'; |
| 3 | +import { GLOBAL_POSTS_SLIM } from '$/lib/server/posts/services/get-posts'; |
| 4 | +import fs from 'node:fs'; |
| 5 | +import path from 'node:path'; |
| 6 | + |
| 7 | +export const prerender = true; |
| 8 | + |
| 9 | +export async function GET() { |
| 10 | + const categories = extractCategories(GLOBAL_POSTS_SLIM); |
| 11 | + |
| 12 | + // read everything in the src/routes folder, then only considers the ones with a +page.svelte file |
| 13 | + const routes = fs |
| 14 | + .readdirSync(path.join('src', 'routes'), { recursive: true }) |
| 15 | + .filter((file) => typeof file === 'string' && file.endsWith('+page.svelte')) |
| 16 | + .map((file) => { |
| 17 | + if (typeof file !== 'string') { |
| 18 | + throw new Error('File is not a string'); |
| 19 | + } |
| 20 | + |
| 21 | + const pathname = file.replace(/\/\+page\.svelte|\+page\.svelte/, ''); |
| 22 | + |
| 23 | + const route = website.url + '/' + pathname; |
| 24 | + |
| 25 | + if (route.includes('[post]')) { |
| 26 | + return GLOBAL_POSTS_SLIM.map(({ slug, date }) => ({ |
| 27 | + url: route.replace('[post]', slug), |
| 28 | + date: new Date(date).toISOString() |
| 29 | + })); |
| 30 | + } |
| 31 | + |
| 32 | + if (route.includes('[category]')) { |
| 33 | + return categories.map((slug) => ({ |
| 34 | + url: route.replace('[category]', slug), |
| 35 | + date: new Date().toISOString() |
| 36 | + })); |
| 37 | + } |
| 38 | + |
| 39 | + return { |
| 40 | + url: route, |
| 41 | + date: new Date().toISOString() |
| 42 | + }; |
| 43 | + }) |
| 44 | + .flat(); |
| 45 | + |
| 46 | + const urls = routes.map((route) => { |
| 47 | + return ` |
| 48 | + <url> |
| 49 | + <loc>${route.url}</loc> |
| 50 | + <lastmod>${route.date}</lastmod> |
| 51 | + <changefreq>weekly</changefreq> |
| 52 | + <priority>0.5</priority> |
| 53 | + </url> |
| 54 | + `; |
| 55 | + }); |
| 56 | + |
| 57 | + return new Response( |
| 58 | + ` |
| 59 | + <?xml version="1.0" encoding="UTF-8" ?> |
| 60 | + <urlset |
| 61 | + xmlns="https://www.sitemaps.org/schemas/sitemap/0.9" |
| 62 | + xmlns:xhtml="https://www.w3.org/1999/xhtml" |
| 63 | + xmlns:mobile="https://www.google.com/schemas/sitemap-mobile/1.0" |
| 64 | + xmlns:news="https://www.google.com/schemas/sitemap-news/0.9" |
| 65 | + xmlns:image="https://www.google.com/schemas/sitemap-image/1.1" |
| 66 | + xmlns:video="https://www.google.com/schemas/sitemap-video/1.1" |
| 67 | + > |
| 68 | + <url> |
| 69 | + <loc>${website.url}</loc> |
| 70 | + <lastmod>${new Date().toISOString()}</lastmod> |
| 71 | + <changefreq>weekly</changefreq> |
| 72 | + <priority>1.0</priority> |
| 73 | + </url> |
| 74 | + ${urls.join('')} |
| 75 | + </urlset>`.trim(), |
| 76 | + { |
| 77 | + headers: { |
| 78 | + 'Content-Type': 'application/xml' |
| 79 | + } |
| 80 | + } |
| 81 | + ); |
| 82 | +} |
0 commit comments