Last active
May 2, 2025 16:54
-
-
Save vincentorback/d8f6f5f45df67cf119766e1658c3a04a to your computer and use it in GitHub Desktop.
Product stock with Snipcart Javascript API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const API_KEY = 'XXXXXXXXXXXXXXXXX' | |
export const fetchStock = async (productId = '') => { | |
try { | |
const response = await fetch(`https://app.snipcart.com/api/products/${productId}`, { | |
headers: { | |
'Authorization': 'Basic ' + Buffer.from(API_KEY + ':').toString('base64'), | |
'Accept': 'application/json', | |
}, | |
}).then(res => res.json()) | |
if (productId !== '') { | |
const product = response | |
if (product.userDefinedId) { | |
return { | |
id: product.userDefinedId, | |
stock: product.allowOutOfStockPurchases ? true : product.stock, | |
} | |
} else { | |
return { | |
error: true, | |
message: `No product with id: "${productId}" found.` | |
} | |
} | |
} else { | |
if (response.items) { | |
let stockProducts = [] | |
const products = response.items | |
if (products.length > 0) { | |
stockProducts = products.map(product => { | |
return { | |
id: product.userDefinedId, | |
stock: product.allowOutOfStockPurchases ? true : product.stock, | |
} | |
}) | |
} | |
return stockProducts | |
} else { | |
return { | |
error: true, | |
message: 'No products found.' | |
} | |
} | |
} | |
} catch(err) { | |
return { | |
error: true, | |
message: String(err) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment