import { HIDDEN_PRODUCT_TAG, SHOPIFY_GRAPHQL_API_ENDPOINT } from 'lib/constants'; import { isShopifyError } from 'lib/type-guards'; import { addToCartMutation, createCartMutation, editCartItemsMutation, removeFromCartMutation } from './mutations/cart'; import { getCartQuery } from './queries/cart'; import { getCollectionProductsQuery, getCollectionQuery, getCollectionsQuery } from './queries/collection'; import { getMenuQuery } from './queries/menu'; import { getPageQuery, getPagesQuery } from './queries/page'; import { getProductQuery, getProductRecommendationsQuery, getProductsQuery } from './queries/product'; import { Cart, Collection, Connection, Menu, Page, Product, ShopifyAddToCartOperation, ShopifyCart, ShopifyCartOperation, ShopifyCollection, ShopifyCollectionOperation, ShopifyCollectionProductsOperation, ShopifyCollectionsOperation, ShopifyCreateCartOperation, ShopifyMenuOperation, ShopifyPageOperation, ShopifyPagesOperation, ShopifyProduct, ShopifyProductOperation, ShopifyProductRecommendationsOperation, ShopifyProductsOperation, ShopifyRemoveFromCartOperation, ShopifyUpdateCartOperation } from './types'; const domain = `https://${process.env.SHOPIFY_STORE_DOMAIN!}`; const endpoint = `${domain}${SHOPIFY_GRAPHQL_API_ENDPOINT}`; const key = process.env.SHOPIFY_STOREFRONT_ACCESS_TOKEN!; type ExtractVariables = T extends { variables: object } ? T['variables'] : never; export async function shopifyFetch({ query, variables, headers, cache = 'force-cache' }: { query: string; variables?: ExtractVariables; headers?: HeadersInit; cache?: RequestCache; }): Promise<{ status: number; body: T } | never> { try { const result = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Shopify-Storefront-Access-Token': key, ...headers }, body: JSON.stringify({ ...(query && { query }), ...(variables && { variables }) }), cache, next: { revalidate: 900 } // 15 minutes }); const body = await result.json(); if (body.errors) { throw body.errors[0]; } return { status: result.status, body }; } catch (e) { if (isShopifyError(e)) { throw { status: e.status || 500, message: e.message, query }; } throw { error: e, query }; } } const removeEdgesAndNodes = (array: Connection) => { return array.edges.map((edge) => edge?.node); }; const reshapeCart = (cart: ShopifyCart): Cart => { if (!cart.cost?.totalTaxAmount) { cart.cost.totalTaxAmount = { amount: '0.0', currencyCode: 'USD' }; } return { ...cart, lines: removeEdgesAndNodes(cart.lines) }; }; const reshapeCollection = (collection: ShopifyCollection): Collection | undefined => { if (!collection) { return undefined; } return { ...collection, path: `/search/${collection.handle}` }; }; const reshapeCollections = (collections: ShopifyCollection[]) => { const reshapedCollections = []; for (const collection of collections) { if (collection) { const reshapedCollection = reshapeCollection(collection); if (reshapedCollection) { reshapedCollections.push(reshapedCollection); } } } return reshapedCollections; }; const reshapeProduct = (product: ShopifyProduct, filterHiddenProducts: boolean = true) => { if (!product || (filterHiddenProducts && product.tags.includes(HIDDEN_PRODUCT_TAG))) { return undefined; } const { images, variants, ...rest } = product; return { ...rest, images: removeEdgesAndNodes(images), variants: removeEdgesAndNodes(variants) }; }; const reshapeProducts = (products: ShopifyProduct[]) => { const reshapedProducts = []; for (const product of products) { if (product) { const reshapedProduct = reshapeProduct(product); if (reshapedProduct) { reshapedProducts.push(reshapedProduct); } } } return reshapedProducts; }; export async function createCart(): Promise { const res = await shopifyFetch({ query: createCartMutation, cache: 'no-store' }); return reshapeCart(res.body.data.cartCreate.cart); } export async function addToCart( cartId: string, lines: { merchandiseId: string; quantity: number }[] ): Promise { const res = await shopifyFetch({ query: addToCartMutation, variables: { cartId, lines }, cache: 'no-store' }); return reshapeCart(res.body.data.cartLinesAdd.cart); } export async function removeFromCart(cartId: string, lineIds: string[]): Promise { const res = await shopifyFetch({ query: removeFromCartMutation, variables: { cartId, lineIds }, cache: 'no-store' }); return reshapeCart(res.body.data.cartLinesRemove.cart); } export async function updateCart( cartId: string, lines: { id: string; merchandiseId: string; quantity: number }[] ): Promise { const res = await shopifyFetch({ query: editCartItemsMutation, variables: { cartId, lines }, cache: 'no-store' }); return reshapeCart(res.body.data.cartLinesUpdate.cart); } export async function getCart(cartId: string): Promise { const res = await shopifyFetch({ query: getCartQuery, variables: { cartId }, cache: 'no-store' }); if (!res.body.data.cart) { return null; } return reshapeCart(res.body.data.cart); } export async function getCollection(handle: string): Promise { const res = await shopifyFetch({ query: getCollectionQuery, variables: { handle } }); return reshapeCollection(res.body.data.collection); } export async function getCollectionProducts(handle: string): Promise { const res = await shopifyFetch({ query: getCollectionProductsQuery, variables: { handle } }); if (!res.body.data.collection) { console.log('No collection found for handle', handle); return []; } return reshapeProducts(removeEdgesAndNodes(res.body.data.collection.products)); } export async function getCollections(): Promise { const res = await shopifyFetch({ query: getCollectionsQuery }); const shopifyCollections = removeEdgesAndNodes(res.body?.data?.collections); const collections = [ { handle: '', title: 'All', description: 'All products', seo: { title: 'All', description: 'All products' }, path: '/search', updatedAt: new Date().toISOString() }, // Filter out the `hidden` collections. // Collections that start with `hidden-*` need to be hidden on the search page. ...reshapeCollections(shopifyCollections).filter( (collection) => !collection.handle.startsWith('hidden') ) ]; return collections; } export async function getMenu(handle: string): Promise { const res = await shopifyFetch({ query: getMenuQuery, variables: { handle } }); return ( res.body?.data?.menu?.items.map((item: { title: string; url: string }) => ({ title: item.title, path: item.url.replace(domain, '').replace('/collections', '/search').replace('/pages', '') })) || [] ); } export async function getPage(handle: string): Promise { const res = await shopifyFetch({ query: getPageQuery, variables: { handle } }); return res.body.data.pageByHandle; } export async function getPages(): Promise { const res = await shopifyFetch({ query: getPagesQuery }); return removeEdgesAndNodes(res.body.data.pages); } export async function getProduct(handle: string): Promise { const res = await shopifyFetch({ query: getProductQuery, variables: { handle } }); return reshapeProduct(res.body.data.product, false); } export async function getProductRecommendations(productId: string): Promise { const res = await shopifyFetch({ query: getProductRecommendationsQuery, variables: { productId } }); return reshapeProducts(res.body.data.productRecommendations); } export async function getProducts({ query, reverse, sortKey }: { query?: string; reverse?: boolean; sortKey?: string; }): Promise { const res = await shopifyFetch({ query: getProductsQuery, variables: { query, reverse, sortKey } }); return reshapeProducts(removeEdgesAndNodes(res.body.data.products)); }