This commit is contained in:
karl 2025-03-26 16:02:22 -04:00
parent e8d5b6e789
commit ad785c9f9a
2 changed files with 195 additions and 190 deletions

View File

@ -48,4 +48,11 @@ export const TAGS = {
export const HIDDEN_PRODUCT_TAG = 'nextjs-frontend-hidden' export const HIDDEN_PRODUCT_TAG = 'nextjs-frontend-hidden'
export const DEFAULT_OPTION = 'Default Title' export const DEFAULT_OPTION = 'Default Title'
export const SHOPIFY_GRAPHQL_API_ENDPOINT = `https://${process.env.SHOPIFY_STORE_DOMAIN}/api/2023-01/graphql.json`
export function getShopifyGraphqlEndpoint() {
const storeDomain = process.env.SHOPIFY_STORE_DOMAIN
if (!storeDomain) {
throw new Error('SHOPIFY_STORE_DOMAIN environment variable is not set')
}
return `https://${storeDomain}/api/2023-01/graphql.json`
}

View File

@ -1,36 +1,36 @@
import { import {
HIDDEN_PRODUCT_TAG, HIDDEN_PRODUCT_TAG,
SHOPIFY_GRAPHQL_API_ENDPOINT, getShopifyGraphqlEndpoint,
TAGS TAGS,
} from 'lib/constants'; } from 'lib/constants'
import { isShopifyError } from 'lib/type-guards'; import { isShopifyError } from 'lib/type-guards'
import { ensureStartsWith } from 'lib/utils'; import { ensureStartsWith } from 'lib/utils'
import { import {
revalidateTag, revalidateTag,
unstable_cacheTag as cacheTag, unstable_cacheTag as cacheTag,
unstable_cacheLife as cacheLife unstable_cacheLife as cacheLife,
} from 'next/cache'; } from 'next/cache'
import { cookies, headers } from 'next/headers'; import { cookies, headers } from 'next/headers'
import { NextRequest, NextResponse } from 'next/server'; import { NextRequest, NextResponse } from 'next/server'
import { import {
addToCartMutation, addToCartMutation,
createCartMutation, createCartMutation,
editCartItemsMutation, editCartItemsMutation,
removeFromCartMutation removeFromCartMutation,
} from './mutations/cart'; } from './mutations/cart'
import { getCartQuery } from './queries/cart'; import { getCartQuery } from './queries/cart'
import { import {
getCollectionProductsQuery, getCollectionProductsQuery,
getCollectionQuery, getCollectionQuery,
getCollectionsQuery getCollectionsQuery,
} from './queries/collection'; } from './queries/collection'
import { getMenuQuery } from './queries/menu'; import { getMenuQuery } from './queries/menu'
import { getPageQuery, getPagesQuery } from './queries/page'; import { getPageQuery, getPagesQuery } from './queries/page'
import { import {
getProductQuery, getProductQuery,
getProductRecommendationsQuery, getProductRecommendationsQuery,
getProductsQuery getProductsQuery,
} from './queries/product'; } from './queries/product'
import { import {
Cart, Cart,
Collection, Collection,
@ -55,292 +55,290 @@ import {
ShopifyProductRecommendationsOperation, ShopifyProductRecommendationsOperation,
ShopifyProductsOperation, ShopifyProductsOperation,
ShopifyRemoveFromCartOperation, ShopifyRemoveFromCartOperation,
ShopifyUpdateCartOperation ShopifyUpdateCartOperation,
} from './types'; } from './types'
const domain = process.env.SHOPIFY_STORE_DOMAIN const domain = process.env.SHOPIFY_STORE_DOMAIN
? ensureStartsWith(process.env.SHOPIFY_STORE_DOMAIN, 'https://') ? ensureStartsWith(process.env.SHOPIFY_STORE_DOMAIN, 'https://')
: ''; : ''
const endpoint = `${domain}${SHOPIFY_GRAPHQL_API_ENDPOINT}`; const key = process.env.SHOPIFY_STOREFRONT_ACCESS_TOKEN!
const key = process.env.SHOPIFY_STOREFRONT_ACCESS_TOKEN!;
type ExtractVariables<T> = T extends { variables: object } type ExtractVariables<T> = T extends { variables: object }
? T['variables'] ? T['variables']
: never; : never
export async function shopifyFetch<T>({ export async function shopifyFetch<T>({
headers, headers,
query, query,
variables variables,
}: { }: {
headers?: HeadersInit; headers?: HeadersInit
query: string; query: string
variables?: ExtractVariables<T>; variables?: ExtractVariables<T>
}): Promise<{ status: number; body: T } | never> { }): Promise<{ status: number; body: T } | never> {
try { try {
const endpoint = getShopifyGraphqlEndpoint()
const result = await fetch(endpoint, { const result = await fetch(endpoint, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'X-Shopify-Storefront-Access-Token': key, 'X-Shopify-Storefront-Access-Token': key,
...headers ...headers,
}, },
body: JSON.stringify({ body: JSON.stringify({
...(query && { query }), ...(query && { query }),
...(variables && { variables }) ...(variables && { variables }),
}),
}) })
});
const body = await result.json(); const body = await result.json()
if (body.errors) { if (body.errors) {
throw body.errors[0]; throw body.errors[0]
} }
return { return {
status: result.status, status: result.status,
body body,
}; }
} catch (e) { } catch (e) {
if (isShopifyError(e)) { if (isShopifyError(e)) {
throw { throw {
cause: e.cause?.toString() || 'unknown', cause: e.cause?.toString() || 'unknown',
status: e.status || 500, status: e.status || 500,
message: e.message, message: e.message,
query query,
}; }
} }
throw { throw {
error: e, error: e,
query query,
}; }
} }
} }
const removeEdgesAndNodes = <T>(array: Connection<T>): T[] => { const removeEdgesAndNodes = <T>(array: Connection<T>): T[] => {
return array.edges.map((edge) => edge?.node); return array.edges.map((edge) => edge?.node)
}; }
const reshapeCart = (cart: ShopifyCart): Cart => { const reshapeCart = (cart: ShopifyCart): Cart => {
if (!cart.cost?.totalTaxAmount) { if (!cart.cost?.totalTaxAmount) {
cart.cost.totalTaxAmount = { cart.cost.totalTaxAmount = {
amount: '0.0', amount: '0.0',
currencyCode: cart.cost.totalAmount.currencyCode currencyCode: cart.cost.totalAmount.currencyCode,
}; }
} }
return { return {
...cart, ...cart,
lines: removeEdgesAndNodes(cart.lines) lines: removeEdgesAndNodes(cart.lines),
}; }
}; }
const reshapeCollection = ( const reshapeCollection = (
collection: ShopifyCollection collection: ShopifyCollection,
): Collection | undefined => { ): Collection | undefined => {
if (!collection) { if (!collection) {
return undefined; return undefined
} }
return { return {
...collection, ...collection,
path: `/search/${collection.handle}` path: `/search/${collection.handle}`,
}; }
}; }
const reshapeCollections = (collections: ShopifyCollection[]) => { const reshapeCollections = (collections: ShopifyCollection[]) => {
const reshapedCollections = []; const reshapedCollections = []
for (const collection of collections) { for (const collection of collections) {
if (collection) { if (collection) {
const reshapedCollection = reshapeCollection(collection); const reshapedCollection = reshapeCollection(collection)
if (reshapedCollection) { if (reshapedCollection) {
reshapedCollections.push(reshapedCollection); reshapedCollections.push(reshapedCollection)
} }
} }
} }
return reshapedCollections; return reshapedCollections
}; }
const reshapeImages = (images: Connection<Image>, productTitle: string) => { const reshapeImages = (images: Connection<Image>, productTitle: string) => {
const flattened = removeEdgesAndNodes(images); const flattened = removeEdgesAndNodes(images)
return flattened.map((image) => { return flattened.map((image) => {
const filename = image.url.match(/.*\/(.*)\..*/)?.[1]; const filename = image.url.match(/.*\/(.*)\..*/)?.[1]
return { return {
...image, ...image,
altText: image.altText || `${productTitle} - ${filename}` altText: image.altText || `${productTitle} - ${filename}`,
}; }
}); })
}; }
const reshapeProduct = ( const reshapeProduct = (
product: ShopifyProduct, product: ShopifyProduct,
filterHiddenProducts: boolean = true filterHiddenProducts: boolean = true,
) => { ) => {
if ( if (
!product || !product ||
(filterHiddenProducts && product.tags.includes(HIDDEN_PRODUCT_TAG)) (filterHiddenProducts && product.tags.includes(HIDDEN_PRODUCT_TAG))
) { ) {
return undefined; return undefined
} }
const { images, variants, ...rest } = product; const { images, variants, ...rest } = product
return { return {
...rest, ...rest,
images: reshapeImages(images, product.title), images: reshapeImages(images, product.title),
variants: removeEdgesAndNodes(variants) variants: removeEdgesAndNodes(variants),
}; }
}; }
const reshapeProducts = (products: ShopifyProduct[]) => { const reshapeProducts = (products: ShopifyProduct[]) => {
const reshapedProducts = []; const reshapedProducts = []
for (const product of products) { for (const product of products) {
if (product) { if (product) {
const reshapedProduct = reshapeProduct(product); const reshapedProduct = reshapeProduct(product)
if (reshapedProduct) { if (reshapedProduct) {
reshapedProducts.push(reshapedProduct); reshapedProducts.push(reshapedProduct)
} }
} }
} }
return reshapedProducts; return reshapedProducts
}; }
export async function createCart(): Promise<Cart> { export async function createCart(): Promise<Cart> {
const res = await shopifyFetch<ShopifyCreateCartOperation>({ const res = await shopifyFetch<ShopifyCreateCartOperation>({
query: createCartMutation query: createCartMutation,
}); })
return reshapeCart(res.body.data.cartCreate.cart); return reshapeCart(res.body.data.cartCreate.cart)
} }
export async function addToCart( export async function addToCart(
lines: { merchandiseId: string; quantity: number }[] lines: { merchandiseId: string; quantity: number }[],
): Promise<Cart> { ): Promise<Cart> {
const cartId = (await cookies()).get('cartId')?.value!; const cartId = (await cookies()).get('cartId')?.value!
const res = await shopifyFetch<ShopifyAddToCartOperation>({ const res = await shopifyFetch<ShopifyAddToCartOperation>({
query: addToCartMutation, query: addToCartMutation,
variables: { variables: {
cartId, cartId,
lines lines,
} },
}); })
return reshapeCart(res.body.data.cartLinesAdd.cart); return reshapeCart(res.body.data.cartLinesAdd.cart)
} }
export async function removeFromCart(lineIds: string[]): Promise<Cart> { export async function removeFromCart(lineIds: string[]): Promise<Cart> {
const cartId = (await cookies()).get('cartId')?.value!; const cartId = (await cookies()).get('cartId')?.value!
const res = await shopifyFetch<ShopifyRemoveFromCartOperation>({ const res = await shopifyFetch<ShopifyRemoveFromCartOperation>({
query: removeFromCartMutation, query: removeFromCartMutation,
variables: { variables: {
cartId, cartId,
lineIds lineIds,
} },
}); })
return reshapeCart(res.body.data.cartLinesRemove.cart); return reshapeCart(res.body.data.cartLinesRemove.cart)
} }
export async function updateCart( export async function updateCart(
lines: { id: string; merchandiseId: string; quantity: number }[] lines: { id: string; merchandiseId: string; quantity: number }[],
): Promise<Cart> { ): Promise<Cart> {
const cartId = (await cookies()).get('cartId')?.value!; const cartId = (await cookies()).get('cartId')?.value!
const res = await shopifyFetch<ShopifyUpdateCartOperation>({ const res = await shopifyFetch<ShopifyUpdateCartOperation>({
query: editCartItemsMutation, query: editCartItemsMutation,
variables: { variables: {
cartId, cartId,
lines lines,
} },
}); })
return reshapeCart(res.body.data.cartLinesUpdate.cart); return reshapeCart(res.body.data.cartLinesUpdate.cart)
} }
export async function getCart(): Promise<Cart | undefined> { export async function getCart(): Promise<Cart | undefined> {
const cartId = (await cookies()).get('cartId')?.value; const cartId = (await cookies()).get('cartId')?.value
if (!cartId) { if (!cartId) {
return undefined; return undefined
} }
const res = await shopifyFetch<ShopifyCartOperation>({ const res = await shopifyFetch<ShopifyCartOperation>({
query: getCartQuery, query: getCartQuery,
variables: { cartId } variables: { cartId },
}); })
// Old carts becomes `null` when you checkout. // Old carts becomes `null` when you checkout.
if (!res.body.data.cart) { if (!res.body.data.cart) {
return undefined; return undefined
} }
return reshapeCart(res.body.data.cart); return reshapeCart(res.body.data.cart)
} }
export async function getCollection( export async function getCollection(
handle: string handle: string,
): Promise<Collection | undefined> { ): Promise<Collection | undefined> {
'use cache'; 'use cache'
cacheTag(TAGS.collections); cacheTag(TAGS.collections)
cacheLife('days'); cacheLife('days')
const res = await shopifyFetch<ShopifyCollectionOperation>({ const res = await shopifyFetch<ShopifyCollectionOperation>({
query: getCollectionQuery, query: getCollectionQuery,
variables: { variables: {
handle handle,
} },
}); })
return reshapeCollection(res.body.data.collection); return reshapeCollection(res.body.data.collection)
} }
export async function getCollectionProducts({ export async function getCollectionProducts({
collection, collection,
reverse, reverse,
sortKey sortKey,
}: { }: {
collection: string; collection: string
reverse?: boolean; reverse?: boolean
sortKey?: string; sortKey?: string
}): Promise<Product[]> { }): Promise<Product[]> {
'use cache'; 'use cache'
cacheTag(TAGS.collections, TAGS.products); cacheTag(TAGS.collections, TAGS.products)
cacheLife('days'); cacheLife('days')
const res = await shopifyFetch<ShopifyCollectionProductsOperation>({ const res = await shopifyFetch<ShopifyCollectionProductsOperation>({
query: getCollectionProductsQuery, query: getCollectionProductsQuery,
variables: { variables: {
handle: collection, handle: collection,
reverse, reverse,
sortKey: sortKey === 'CREATED_AT' ? 'CREATED' : sortKey sortKey: sortKey === 'CREATED_AT' ? 'CREATED' : sortKey,
} },
}); })
if (!res.body.data.collection) { if (!res.body.data.collection) {
console.log(`No collection found for \`${collection}\``); console.log(`No collection found for \`${collection}\``)
return []; return []
} }
return reshapeProducts( return reshapeProducts(removeEdgesAndNodes(res.body.data.collection.products))
removeEdgesAndNodes(res.body.data.collection.products)
);
} }
export async function getCollections(): Promise<Collection[]> { export async function getCollections(): Promise<Collection[]> {
'use cache'; 'use cache'
cacheTag(TAGS.collections); cacheTag(TAGS.collections)
cacheLife('days'); cacheLife('days')
const res = await shopifyFetch<ShopifyCollectionsOperation>({ const res = await shopifyFetch<ShopifyCollectionsOperation>({
query: getCollectionsQuery query: getCollectionsQuery,
}); })
const shopifyCollections = removeEdgesAndNodes(res.body?.data?.collections); const shopifyCollections = removeEdgesAndNodes(res.body?.data?.collections)
const collections = [ const collections = [
{ {
handle: '', handle: '',
@ -348,32 +346,32 @@ export async function getCollections(): Promise<Collection[]> {
description: 'All products', description: 'All products',
seo: { seo: {
title: 'All', title: 'All',
description: 'All products' description: 'All products',
}, },
path: '/search', path: '/search',
updatedAt: new Date().toISOString() updatedAt: new Date().toISOString(),
}, },
// Filter out the `hidden` collections. // Filter out the `hidden` collections.
// Collections that start with `hidden-*` need to be hidden on the search page. // Collections that start with `hidden-*` need to be hidden on the search page.
...reshapeCollections(shopifyCollections).filter( ...reshapeCollections(shopifyCollections).filter(
(collection) => !collection.handle.startsWith('hidden') (collection) => !collection.handle.startsWith('hidden'),
) ),
]; ]
return collections; return collections
} }
export async function getMenu(handle: string): Promise<Menu[]> { export async function getMenu(handle: string): Promise<Menu[]> {
'use cache'; 'use cache'
cacheTag(TAGS.collections); cacheTag(TAGS.collections)
cacheLife('days'); cacheLife('days')
const res = await shopifyFetch<ShopifyMenuOperation>({ const res = await shopifyFetch<ShopifyMenuOperation>({
query: getMenuQuery, query: getMenuQuery,
variables: { variables: {
handle handle,
} },
}); })
return ( return (
res.body?.data?.menu?.items.map((item: { title: string; url: string }) => ({ res.body?.data?.menu?.items.map((item: { title: string; url: string }) => ({
@ -381,83 +379,83 @@ export async function getMenu(handle: string): Promise<Menu[]> {
path: item.url path: item.url
.replace(domain, '') .replace(domain, '')
.replace('/collections', '/search') .replace('/collections', '/search')
.replace('/pages', '') .replace('/pages', ''),
})) || [] })) || []
); )
} }
export async function getPage(handle: string): Promise<Page> { export async function getPage(handle: string): Promise<Page> {
const res = await shopifyFetch<ShopifyPageOperation>({ const res = await shopifyFetch<ShopifyPageOperation>({
query: getPageQuery, query: getPageQuery,
variables: { handle } variables: { handle },
}); })
return res.body.data.pageByHandle; return res.body.data.pageByHandle
} }
export async function getPages(): Promise<Page[]> { export async function getPages(): Promise<Page[]> {
const res = await shopifyFetch<ShopifyPagesOperation>({ const res = await shopifyFetch<ShopifyPagesOperation>({
query: getPagesQuery query: getPagesQuery,
}); })
return removeEdgesAndNodes(res.body.data.pages); return removeEdgesAndNodes(res.body.data.pages)
} }
export async function getProduct(handle: string): Promise<Product | undefined> { export async function getProduct(handle: string): Promise<Product | undefined> {
'use cache'; 'use cache'
cacheTag(TAGS.products); cacheTag(TAGS.products)
cacheLife('days'); cacheLife('days')
const res = await shopifyFetch<ShopifyProductOperation>({ const res = await shopifyFetch<ShopifyProductOperation>({
query: getProductQuery, query: getProductQuery,
variables: { variables: {
handle handle,
} },
}); })
return reshapeProduct(res.body.data.product, false); return reshapeProduct(res.body.data.product, false)
} }
export async function getProductRecommendations( export async function getProductRecommendations(
productId: string productId: string,
): Promise<Product[]> { ): Promise<Product[]> {
'use cache'; 'use cache'
cacheTag(TAGS.products); cacheTag(TAGS.products)
cacheLife('days'); cacheLife('days')
const res = await shopifyFetch<ShopifyProductRecommendationsOperation>({ const res = await shopifyFetch<ShopifyProductRecommendationsOperation>({
query: getProductRecommendationsQuery, query: getProductRecommendationsQuery,
variables: { variables: {
productId productId,
} },
}); })
return reshapeProducts(res.body.data.productRecommendations); return reshapeProducts(res.body.data.productRecommendations)
} }
export async function getProducts({ export async function getProducts({
query, query,
reverse, reverse,
sortKey sortKey,
}: { }: {
query?: string; query?: string
reverse?: boolean; reverse?: boolean
sortKey?: string; sortKey?: string
}): Promise<Product[]> { }): Promise<Product[]> {
'use cache'; 'use cache'
cacheTag(TAGS.products); cacheTag(TAGS.products)
cacheLife('days'); cacheLife('days')
const res = await shopifyFetch<ShopifyProductsOperation>({ const res = await shopifyFetch<ShopifyProductsOperation>({
query: getProductsQuery, query: getProductsQuery,
variables: { variables: {
query, query,
reverse, reverse,
sortKey sortKey,
} },
}); })
return reshapeProducts(removeEdgesAndNodes(res.body.data.products)); return reshapeProducts(removeEdgesAndNodes(res.body.data.products))
} }
// This is called from `app/api/revalidate.ts` so providers can control revalidation logic. // This is called from `app/api/revalidate.ts` so providers can control revalidation logic.
@ -467,35 +465,35 @@ export async function revalidate(req: NextRequest): Promise<NextResponse> {
const collectionWebhooks = [ const collectionWebhooks = [
'collections/create', 'collections/create',
'collections/delete', 'collections/delete',
'collections/update' 'collections/update',
]; ]
const productWebhooks = [ const productWebhooks = [
'products/create', 'products/create',
'products/delete', 'products/delete',
'products/update' 'products/update',
]; ]
const topic = (await headers()).get('x-shopify-topic') || 'unknown'; const topic = (await headers()).get('x-shopify-topic') || 'unknown'
const secret = req.nextUrl.searchParams.get('secret'); const secret = req.nextUrl.searchParams.get('secret')
const isCollectionUpdate = collectionWebhooks.includes(topic); const isCollectionUpdate = collectionWebhooks.includes(topic)
const isProductUpdate = productWebhooks.includes(topic); const isProductUpdate = productWebhooks.includes(topic)
if (!secret || secret !== process.env.SHOPIFY_REVALIDATION_SECRET) { if (!secret || secret !== process.env.SHOPIFY_REVALIDATION_SECRET) {
console.error('Invalid revalidation secret.'); console.error('Invalid revalidation secret.')
return NextResponse.json({ status: 401 }); return NextResponse.json({ status: 401 })
} }
if (!isCollectionUpdate && !isProductUpdate) { if (!isCollectionUpdate && !isProductUpdate) {
// We don't need to revalidate anything for any other topics. // We don't need to revalidate anything for any other topics.
return NextResponse.json({ status: 200 }); return NextResponse.json({ status: 200 })
} }
if (isCollectionUpdate) { if (isCollectionUpdate) {
revalidateTag(TAGS.collections); revalidateTag(TAGS.collections)
} }
if (isProductUpdate) { if (isProductUpdate) {
revalidateTag(TAGS.products); revalidateTag(TAGS.products)
} }
return NextResponse.json({ status: 200, revalidated: true, now: Date.now() }); return NextResponse.json({ status: 200, revalidated: true, now: Date.now() })
} }