diff --git a/src/routes/feed/products.xml/+server.ts b/src/routes/feed/products.xml/+server.ts new file mode 100644 index 0000000..488db4e --- /dev/null +++ b/src/routes/feed/products.xml/+server.ts @@ -0,0 +1,94 @@ +import { error } from '@sveltejs/kit' +import type { RequestHandler } from './$types' +import { fetchSwell } from '$utils/functions/shopServer' +import { fetchAPI, getAssetUrlKey } from '$utils/api' + +const gCategories = [ + { + id: '61851d83cd16416c78a8e5ef', + type: 'Posters, Prints, & Visual Artwork', + value: 'Home & Garden > Decor > Artwork > Posters, Prints, & Visual Artwork' + } +] + +export const GET: RequestHandler = async ({ url, setHeaders }) => { + try { + const products = [] + + // Get products from Swell API + const shopProducts: any = await fetchSwell(`/products`) + + // Get products from site API + const siteProducts = await fetchAPI(`query { + products: product (filter: { status: { _eq: "published" }}) { + location { slug } + name + description + details + product_id + photos_product { + directus_files_id { id } + } + } + }`) + + if (shopProducts && siteProducts) { + const { data } = siteProducts + + // Loop through shop products + shopProducts.results.forEach((product: any) => { + // Find matching product from site to platform + const siteProduct = data.products.find((p: any) => p.product_id === product.id) + const category = gCategories.find(p => p.id === product.category_index.id[0]) + + products.push({ + id: product.id, + name: `${product.name} - Poster`, + slug: siteProduct.location.slug, + description: siteProduct.description, + price: product.price, + images: siteProduct.photos_product.map(({ directus_files_id: { id }}: any) => getAssetUrlKey(id, `product-large-jpg`)), + gCategory: category.value, + gType: category.type, + }) + }) + } + + const sitemap = render(url.origin, products) + + 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, products: any[]) => { + return ` + + + ${products.map((product) => ` + ${product.id} + ${product.name} + ${product.description} + ${product.gType} + ${product.gCategory} + ${origin}/shop/poster-${product.slug} + ${product.images[0]} + New + In Stock + ${product.price} EUR + Houses Of + FALSE + ${product.images.slice(1).map((image: any) => ` + ${image} + `).join('')} + + `).join('')} + +` +} \ No newline at end of file