mirror of
https://github.com/vercel/commerce.git
synced 2025-05-18 23:46:58 +00:00
45 lines
1.1 KiB
TypeScript
45 lines
1.1 KiB
TypeScript
import type { OperationContext } from '@commerce/api/operations'
|
|
import type { GetProductOperation } from '../../types/product'
|
|
import type { CommercejsConfig, Provider } from '../index'
|
|
import { normalizeProduct } from '../../utils/normalize-product'
|
|
|
|
export default function getProductOperation({
|
|
commerce,
|
|
}: OperationContext<Provider>) {
|
|
async function getProduct<T extends GetProductOperation>({
|
|
config,
|
|
variables,
|
|
}: {
|
|
query?: string
|
|
variables?: T['variables']
|
|
config?: Partial<CommercejsConfig>
|
|
preview?: boolean
|
|
} = {}): Promise<T['data']> {
|
|
const { sdkFetch } = commerce.getConfig(config)
|
|
|
|
// Fetch a product by its permalink.
|
|
const product = await sdkFetch(
|
|
'products',
|
|
'retrieve',
|
|
variables?.slug || '',
|
|
{
|
|
type: 'permalink',
|
|
}
|
|
)
|
|
|
|
const { data: variants } = await sdkFetch(
|
|
'products',
|
|
'getVariants',
|
|
product.id
|
|
)
|
|
|
|
const productFormatted = normalizeProduct(product, variants)
|
|
|
|
return {
|
|
product: productFormatted,
|
|
}
|
|
}
|
|
|
|
return getProduct
|
|
}
|