Skip to content

Instantly share code, notes, and snippets.

@vincentorback
Last active August 27, 2021 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vincentorback/d8f6f5f45df67cf119766e1658c3a04a to your computer and use it in GitHub Desktop.
Save vincentorback/d8f6f5f45df67cf119766e1658c3a04a to your computer and use it in GitHub Desktop.
Product stock with Snipcart Javascript API
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