Skip to content

Instantly share code, notes, and snippets.

@stlk
Created July 21, 2023 12:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stlk/e41abfea20645f14945a370d687de5f9 to your computer and use it in GitHub Desktop.
Save stlk/e41abfea20645f14945a370d687de5f9 to your computer and use it in GitHub Desktop.
Heureka XML feed Shopify app build on gadget.dev
/**
* Route handler for GET hello
*
* @param { import("gadget-server").RouteContext } request context - Everything for handling this route, like the api client, Fastify request, Fastify reply, etc. More on effect context: https://docs.gadget.dev/guides/extending-with-code#effect-context
*
* @see {@link https://www.fastify.io/docs/latest/Reference/Request}
* @see {@link https://www.fastify.io/docs/latest/Reference/Reply}
*/
module.exports = async ({ request, reply, api, logger, connections }) => {
const js2xmlparser = require("js2xmlparser");
const { myshopify_domain } = request.query;
if (!myshopify_domain) {
return await reply.send("myshopify_domain required");
}
const shop = await api.shopifyShop.findFirst({
filter: {
myshopifyDomain: {
equals: myshopify_domain,
},
}
})
const products = await api.shopifyProduct.findMany({
filter: {
shop: {
equals: shop.id
},
publishedAt: {
isSet: true
}
},
first: 250,
select: {
id: true,
title: true,
handle: true,
body: true,
categoryText: true,
images: {
edges: {
node: {
source: true
}
}
},
variants: {
edges: {
node: {
id: true,
option1: true,
option2: true,
option3: true,
productImage: {
source: true
},
price: true
}
}
},
options: {
edges: {
node: {
name: true,
position: true,
}
}
}
}
});
console.log(products.length)
const shopItems = products.flatMap(product => {
const productHasVariants = product.variants.edges.length > 1
return product.variants.edges.map(variantNode => {
const variant = variantNode.node;
const params = productHasVariants ? product.options.edges.map(option => ({
PARAM_NAME: option.node.name,
VAL: variant[`option${option.node.position}`]
})) : [];
return {
ITEM_ID: variant.id,
ITEMGROUP_ID: product.id,
PRODUCTNAME: product.title,
PRODUCT: product.title,
DESCRIPTION: product.body || '',
URL: `https://${shop.domain}/products/${product.handle}${productHasVariants ? `?variant=${variant.id}` : ''}`,
IMGURL: variant.productImage?.source || product.images.edges[0]?.node?.source,
PRICE_VAT: variant.price,
CATEGORYTEXT: product.categoryText,
DELIVERY_DATE: shop.deliveryDate,
PARAMS: params
}
});
});
const xmlData = js2xmlparser.parse("SHOP", { SHOPITEM: shopItems });
return await reply
.type("application/xml")
.send(xmlData);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment