export default async function main(args) {
const { shopifyStoreName, shopifyApiVersion, shopifyAdminApiKey, productTitle } = args.inputVars;
// Validate input variables
if (!shopifyStoreName || !shopifyApiVersion || !shopifyAdminApiKey || !productTitle) {
return {
next: { path: 'error' },
trace: [{ type: "debug", payload: { message: "Missing required input variables" } }]
};
}
const url = `https://${shopifyStoreName}.myshopify.com/admin/api/${shopifyApiVersion}/products.json?limit=250`;
const headers = {
'X-Shopify-Access-Token': shopifyAdminApiKey,
'Content-Type': 'application/json'
};
try {
// Fetch the list of products
const response = await fetch(url, { method: 'GET', headers: headers });
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const responseBody = await response.json;
// Check if the response contains products
if (!responseBody.products || !Array.isArray(responseBody.products)) {
throw new Error("Invalid or missing response body from Shopify API");
}
// Find the product by title
const product = responseBody.products.find(p => p.title.toLowerCase() === productTitle.toLowerCase());
if (!product) {
return {
next: { path: 'no_match' },
trace: [{ type: "debug", payload: { message: "No matching product found" } }]
};
}
// Extract the required values
const productId = product.id;
const productType = product.product_type;
const bodyHtml = product.body_html;
const adminGraphqlApiId = product.admin_graphql_api_id;
const firstVariant = product.variants[0];
const firstVariantPrice = firstVariant.price;
const inventoryQuantity = firstVariant.inventory_quantity;
const option1 = firstVariant.option1;
const option2 = firstVariant.option2;
return {
outputVars: {
productId,
productType,
firstVariantPrice,
bodyHtml,
adminGraphqlApiId,
inventoryQuantity,
option1,
option2
},
next: { path: 'success' },
trace: [{ type: "debug", payload: { message: "Product found and values extracted" } }]
};
} catch (error) {
return {
next: { path: 'error' },
trace: [{ type: "debug", payload: { message: `Error: ${error.message}` } }]
};
}
}