Skip to content

Commit

Permalink
updated Storefront API version to 2022-10
Browse files Browse the repository at this point in the history
  • Loading branch information
iskurbanov committed Sep 26, 2022
1 parent 1351bdd commit 67cc445
Show file tree
Hide file tree
Showing 6 changed files with 69 additions and 84 deletions.
6 changes: 3 additions & 3 deletions components/ProductCard.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { formatter } from '../utils/helpers'
const ProductCard = ({ product }) => {
const { handle, title } = product.node

const { altText, originalSrc } = product.node.images.edges[0].node
const { altText, url } = product.node.images.edges[0].node

const price = product.node.priceRange.minVariantPrice.amount

Expand All @@ -14,10 +14,10 @@ const ProductCard = ({ product }) => {
href={`/products/${handle}`}
>
<a className="group">
<div className="w-full bg-gray-200 rounded-3xl overflow-hidden">
<div className="w-full overflow-hidden bg-gray-200 rounded-3xl">
<div className="relative group-hover:opacity-75 h-72">
<Image
src={originalSrc}
src={url}
alt={altText}
layout="fill"
objectFit="cover"
Expand Down
24 changes: 5 additions & 19 deletions components/ProductForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export default function ProductForm({ product }) {
id: variant.node.id,
title: product.title,
handle: product.handle,
image: variant.node.image?.originalSrc,
image: variant.node.image?.url,
options: allOptions,
variantTitle: variant.node.title,
variantPrice: variant.node.priceV2.amount,
Expand Down Expand Up @@ -75,30 +75,16 @@ export default function ProductForm({ product }) {
if (productInventory) {
const checkAvailable = productInventory?.variants.edges.filter(item => item.node.id === selectedVariant.id)

if (checkAvailable[0].node.availableForSale) {
if (checkAvailable[0]?.node.availableForSale) {
setAvailable(true)
} else {
setAvailable(false)
}
}
}, [productInventory, selectedVariant])


useEffect(() => {
if (productInventory) {
const checkAvailable = productInventory?.variants.edges.filter(item => item.node.id === selectedVariant.id)

if (checkAvailable[0].node.availableForSale) {
setAvailable(true)
} else {
setAvailable(false)
}
}
}, [productInventory, selectedVariant])


return (
<div className="rounded-2xl p-4 shadow-lg flex flex-col w-full md:w-1/3">
<div className="flex flex-col w-full p-4 shadow-lg rounded-2xl md:w-1/3">
<h2 className="text-2xl font-bold">{product.title}</h2>
<span className="pb-3">{formatter.format(product.variants.edges[0].node.priceV2.amount)}</span>
{
Expand All @@ -121,10 +107,10 @@ export default function ProductForm({ product }) {
onClick={() => {
addToCart(selectedVariant)
}}
className="bg-black rounded-lg text-white px-2 py-3 mt-3 hover:bg-gray-800">Add To Card
className="px-2 py-3 mt-3 text-white bg-black rounded-lg hover:bg-gray-800">Add To Card
</button> :
<button
className="rounded-lg text-white px-2 py-3 mt-3 bg-gray-800 cursor-not-allowed">
className="px-2 py-3 mt-3 text-white bg-gray-800 rounded-lg cursor-not-allowed">
Sold out!
</button>
}
Expand Down
10 changes: 5 additions & 5 deletions components/ProductPageContent.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export default function ProductPageContent({ product }) {
product.images.edges.map((image, i) => {
images.push(
<SwiperSlide key={`slide-${i}`}>
<Image src={image.node.originalSrc} alt={image.node.altText} layout="fill" objectFit="cover" />
<Image src={image.node.url} alt={image.node.altText} layout="fill" objectFit="cover" />
</SwiperSlide>
)
})
Expand All @@ -20,9 +20,9 @@ export default function ProductPageContent({ product }) {

return (
<div>
<div className="flex flex-col justify-center items-center space-y-8 md:flex-row md:items-start md:space-y-0 md:space-x-4 lg:space-x-8 max-w-6xl w-11/12 mx-auto">
<div className="w-full max-w-md border bg-white rounded-2xl overflow-hidden shadow-lg md:w-1/2">
<div className="relative h-96 w-full">
<div className="flex flex-col items-center justify-center w-11/12 max-w-6xl mx-auto space-y-8 md:flex-row md:items-start md:space-y-0 md:space-x-4 lg:space-x-8">
<div className="w-full max-w-md overflow-hidden bg-white border shadow-lg rounded-2xl md:w-1/2">
<div className="relative w-full h-96">
<Swiper
style={{ '--swiper-navigation-color': '#000', '--swiper-pagination-color': '#000' }}
navigation
Expand All @@ -36,7 +36,7 @@ export default function ProductPageContent({ product }) {
</div>
<ProductForm product={product} />
</div>
<p className="pt-16 space-y-8 md:space-x-4 lg:space-x-8 max-w-3xl w-11/12 mx-auto">{product.description}</p>
<p className="w-11/12 max-w-3xl pt-16 mx-auto space-y-8 md:space-x-4 lg:space-x-8">{product.description}</p>
<RecommendedList current={product.id} products={product.collections.edges[0].node.products.edges} />
</div>
)
Expand Down
105 changes: 55 additions & 50 deletions lib/shopify.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,35 @@
const domain = process.env.SHOPIFY_STORE_DOMAIN
const storefrontAccessToken = process.env.SHOPIFY_STOREFRONT_ACCESSTOKEN
const domain = process.env.SHOPIFY_STORE_DOMAIN;
const storefrontAccessToken = process.env.SHOPIFY_STOREFRONT_ACCESSTOKEN;

async function ShopifyData(query) {
const URL = `https://${domain}/api/2021-07/graphql.json`
const URL = `https://${domain}/api/2022-10/graphql.json`;

const options = {
endpoint: URL,
method: "POST",
headers: {
"X-Shopify-Storefront-Access-Token": storefrontAccessToken,
"Accept": "application/json",
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({ query })
}
body: JSON.stringify({ query }),
};

try {
const data = await fetch(URL, options).then(response => {
return response.json()
})
const data = await fetch(URL, options).then((response) => {
return response.json();
});

return data
return data;
} catch (error) {
throw new Error("Products not fetched")
throw new Error("Products not fetched");
}
}

export async function getProductsInCollection() {
const query = `
{
collectionByHandle(handle: "frontpage") {
collection(handle: "frontpage") {
title
products(first: 25) {
edges {
Expand All @@ -45,7 +45,7 @@ export async function getProductsInCollection() {
images(first: 5) {
edges {
node {
originalSrc
url
altText
}
}
Expand All @@ -54,18 +54,19 @@ export async function getProductsInCollection() {
}
}
}
}`
}`;

const response = await ShopifyData(query)
const response = await ShopifyData(query);

const allProducts = response.data.collectionByHandle.products.edges ? response.data.collectionByHandle.products.edges : []
const allProducts = response.data.collection.products.edges
? response.data.collection.products.edges
: [];

return allProducts
return allProducts;
}

export async function getAllProducts() {
const query =
`{
const query = `{
products(first: 250) {
edges {
node {
Expand All @@ -74,19 +75,21 @@ export async function getAllProducts() {
}
}
}
}`
}`;

const response = await ShopifyData(query)
const response = await ShopifyData(query);

const slugs = response.data.products.edges ? response.data.products.edges : []
const slugs = response.data.products.edges
? response.data.products.edges
: [];

return slugs
return slugs;
}

export async function getProduct(handle) {
const query = `
{
productByHandle(handle: "${handle}") {
product(handle: "${handle}") {
collections(first: 1) {
edges {
node {
Expand All @@ -101,11 +104,10 @@ export async function getProduct(handle) {
handle
title
id
totalInventory
images(first: 5) {
edges {
node {
originalSrc
url
altText
}
}
Expand All @@ -123,7 +125,7 @@ export async function getProduct(handle) {
images(first: 5) {
edges {
node {
originalSrc
url
altText
}
}
Expand All @@ -141,7 +143,7 @@ export async function getProduct(handle) {
value
}
image {
originalSrc
url
altText
}
title
Expand All @@ -154,13 +156,15 @@ export async function getProduct(handle) {
}
}
}
}`
}`;

const response = await ShopifyData(query)
const response = await ShopifyData(query);

const product = response.data.productByHandle ? response.data.productByHandle : []
const product = response.data.product
? response.data.product
: [];

return product
return product;
}

export async function createCheckout(id, quantity) {
Expand All @@ -174,22 +178,24 @@ export async function createCheckout(id, quantity) {
webUrl
}
}
}`
}`;

const response = await ShopifyData(query)
const response = await ShopifyData(query);

const checkout = response.data.checkoutCreate.checkout ? response.data.checkoutCreate.checkout : []
const checkout = response.data.checkoutCreate.checkout
? response.data.checkoutCreate.checkout
: [];

return checkout
return checkout;
}

export async function updateCheckout(id, lineItems) {
const lineItemsObject = lineItems.map(item => {
const lineItemsObject = lineItems.map((item) => {
return `{
variantId: "${item.id}",
quantity: ${item.variantQuantity}
}`
})
}`;
});

const query = `
mutation {
Expand All @@ -208,22 +214,21 @@ export async function updateCheckout(id, lineItems) {
}
}
}
}`
}`;

const response = await ShopifyData(query)
const response = await ShopifyData(query);

const checkout = response.data.checkoutLineItemsReplace.checkout ? response.data.checkoutLineItemsReplace.checkout : []
const checkout = response.data.checkoutLineItemsReplace.checkout
? response.data.checkoutLineItemsReplace.checkout
: [];

return checkout
return checkout;
}




export async function recursiveCatalog(cursor = '', initialRequest = true) {
export async function recursiveCatalog(cursor = "", initialRequest = true) {
let data;

if (cursor !== '') {
if (cursor !== "") {
const query = `{
products(after: "${cursor}", first: 250) {
edges {
Expand All @@ -245,7 +250,7 @@ export async function recursiveCatalog(cursor = '', initialRequest = true) {
if (response.data.products.pageInfo.hasNextPage) {
const num = response.data.products.edges.length;
const cursor = response.data.products.edges[num - 1].cursor;
console.log('Cursor: ', cursor);
console.log("Cursor: ", cursor);

return data.concat(await recursiveCatalog(cursor));
} else {
Expand Down Expand Up @@ -280,4 +285,4 @@ export async function recursiveCatalog(cursor = '', initialRequest = true) {
return data;
}
}
}
}
3 changes: 1 addition & 2 deletions pages/api/available.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export default async function send(req, res) {
const storefrontAccessToken = process.env.SHOPIFY_STOREFRONT_ACCESSTOKEN

async function ShopifyData(query) {
const URL = `https://${domain}/api/2021-07/graphql.json`
const URL = `https://${domain}/api/2022-10/graphql.json`

const options = {
endpoint: URL,
Expand Down Expand Up @@ -55,6 +55,5 @@ export default async function send(req, res) {
}

const product = await getProduct(id)

res.json(product)
}
5 changes: 0 additions & 5 deletions pages/products/[product].js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,6 @@ import { getAllProducts, getProduct, recursiveCatalog } from "../../lib/shopify"

export default function ProductPage({ product }) {

// const realId = Buffer.from(product.id, 'base64').toString('utf8').split("/").pop()
// console.log(realId)



return (
<div className="min-h-screen py-12 sm:pt-20">
<ProductPageContent product={product} />
Expand Down

0 comments on commit 67cc445

Please sign in to comment.