From d63db0f473cea36fb83076f821225d603c550d48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fe=CC=81lix=20Pe=CC=81ault?= Date: Tue, 27 Sep 2022 17:30:19 +0200 Subject: [PATCH] Add sitemap.xml --- src/routes/sitemap.xml/+server.ts | 93 +++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 src/routes/sitemap.xml/+server.ts diff --git a/src/routes/sitemap.xml/+server.ts b/src/routes/sitemap.xml/+server.ts new file mode 100644 index 0000000..08d33c3 --- /dev/null +++ b/src/routes/sitemap.xml/+server.ts @@ -0,0 +1,93 @@ +import { error } from '@sveltejs/kit' +import type { RequestHandler } from './$types' +import { fetchAPI } from '$utils/api' + + +export const GET: RequestHandler = async ({ url, setHeaders }) => { + try { + const locations = [] + const products = [] + + // Get dynamic data from API + const res = await fetchAPI(`query { + locations: location (filter: { status: { _eq: "published" }}) { + slug + country { slug } + } + products: product (filter: { status: { _eq: "published" }}) { + location { slug } + } + }`) + + if (res) { + const { data } = res + locations.push(...data.locations) + products.push(...data.products) + } + + // Static pages + const pages = [ + ['/', 1.0, 'daily'], + ['/photos', 1.0, 'daily'], + ['/locations', 0.6, 'weekly'], + ['/shop', 0.8, 'weekly'], + ['/about', 0.6, 'weekly'], + ['/terms', 0.6, 'weekly'], + ['/subscribe', 0.6, 'weekly'], + ['/credits', 0.6, 'monthly'], + ] + + // All pages + const allPages = [ + // Static pages + ...pages.map(([path, priority, frequency]) => ({ + path, + priority, + frequency, + })), + + // Locations + ...locations.map(({ slug, country }) => ({ + path: `/${country.slug}/${slug}`, + priority: 0.7, + frequency: 'monthly', + })), + + // Products + ...products.map(({ location: { slug }}) => ({ + path: `/shop/poster-${slug}`, + priority: 0.7, + frequency: 'monthly', + })), + ] + + const sitemap = render(url.origin, allPages) + + setHeaders({ + 'Content-Type': 'application/xml', + 'Cache-Control': 'max-age=0, s-max-age=600', + }) + + return new Response(sitemap) + } catch (err) { + throw error(500, err.message) + } +} + +const render = (origin: string, pages: any[]) => { + return ` + + ${pages.map(({ path, priority, frequency }) => ` + ${origin}${path} + ${priority} + ${frequency} + `).join('')} +` +} \ No newline at end of file