mirror of
https://github.com/vercel/commerce.git
synced 2025-05-14 13:47:49 +00:00
61 lines
1.6 KiB
TypeScript
61 lines
1.6 KiB
TypeScript
import 'server-only'
|
|
|
|
import type { QueryParams } from '@sanity/client'
|
|
import { client } from './sanity.client'
|
|
|
|
import { draftMode } from 'next/headers'
|
|
|
|
import { revalidateSecret } from './sanity.api'
|
|
|
|
import { homePageQuery } from './queries'
|
|
|
|
import { HomePagePayload } from './sanity.types'
|
|
|
|
export const token = process.env.SANITY_API_READ_TOKEN
|
|
|
|
const DEFAULT_PARAMS = {} as QueryParams
|
|
const DEFAULT_TAGS = [] as string[]
|
|
|
|
export async function sanityFetch<QueryResponse>({
|
|
query,
|
|
params = DEFAULT_PARAMS,
|
|
tags = DEFAULT_TAGS,
|
|
}: {
|
|
query: string
|
|
params?: QueryParams
|
|
tags: string[]
|
|
}): Promise<QueryResponse> {
|
|
const isDraftMode = draftMode().isEnabled
|
|
if (isDraftMode && !token) {
|
|
throw new Error(
|
|
'The `SANITY_API_READ_TOKEN` environment variable is required.',
|
|
)
|
|
}
|
|
|
|
// @TODO this won't be necessary after https://github.com/sanity-io/client/pull/299 lands
|
|
const sanityClient =
|
|
client.config().useCdn && isDraftMode
|
|
? client.withConfig({ useCdn: false })
|
|
: client
|
|
return sanityClient.fetch<QueryResponse>(query, params, {
|
|
// We only cache if there's a revalidation webhook setup
|
|
cache: revalidateSecret ? 'force-cache' : 'no-store',
|
|
...(isDraftMode && {
|
|
cache: undefined,
|
|
token: token,
|
|
perspective: 'previewDrafts',
|
|
}),
|
|
next: {
|
|
...(isDraftMode && { revalidate: 30 }),
|
|
tags,
|
|
},
|
|
})
|
|
}
|
|
|
|
export function getHomePage(locale: string) {
|
|
return sanityFetch<HomePagePayload | null>({
|
|
query: homePageQuery,
|
|
params: { locale },
|
|
tags: ['home', 'products', 'categories'],
|
|
})
|
|
} |