Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save brodsolutions/df74eb59a067404a8e41c1ff665b11c7 to your computer and use it in GitHub Desktop.

Select an option

Save brodsolutions/df74eb59a067404a8e41c1ff665b11c7 to your computer and use it in GitHub Desktop.
<span class="card-text" data-test-stock="variant-stocked-{{id}}">No Stock</span>
<script>
fetch('/graphql', {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer {{ settings.storefront_api.token }}'
},
body: JSON.stringify({
query: `query getVariantsByProductId{
site {
product(entityId: {{ id }}) {
name
variants(first: 25) {
edges {
node {
inventory {
isInStock
byLocation {
edges {
node {
isInStock
availableToSell
locationEntityCode
}
}
}
}
}
}
}
}
}
}`
})
})
.then(res => res.json())
.then(function(data) {
console.log(data);
var inStock = false;
var totalVariantStock = 0;
// Map through each variant and calculate total stock
data.data.site.product.variants.edges.map(function(variant) {
if (variant.node.inventory.isInStock) {
inStock = true;
// Add up all the byLocation availableToSell
variant.node.inventory.byLocation.edges.map(function(location) {
totalVariantStock += location.node.availableToSell;
});
}
});
// Update the stock label based on availability
var stockLabel = document.querySelector('[data-test-stock="variant-stocked-{{id}}"]');
if (totalVariantStock > 0) {
stockLabel.innerHTML = "In Stock" + " (" + totalVariantStock + " available)";
} else {
stockLabel.innerHTML = "Out of Stock";
}
})
.catch(error => console.error(error));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment