1
0
mirror of https://github.com/vercel/commerce.git synced 2025-07-31 22:11:24 +00:00
Files
assets
components
auth
cart
common
icons
product
ProductCard
ProductSlider
ProductView
Swatch
helpers.ts
index.ts
ui
wishlist
config
docs
framework
lib
pages
public
.editorconfig
.env.template
.gitignore
.prettierignore
README.md
codegen.json
global.d.ts
license.md
next-env.d.ts
next.config.js
package.json
postcss.config.js
tailwind.config.js
tsconfig.json
yarn.lock
commerce/components/product/helpers.ts
2020-12-29 20:04:26 -05:00

52 lines
1.3 KiB
TypeScript

import type { ProductNode } from '@framework/api/operations/get-product'
export type SelectedOptions = {
size: string | null
color: string | null
}
export type ProductOption = {
displayName: string
values: any
}
// Returns the available options of a product
export function getProductOptions(product: ProductNode) {
const options = product.productOptions.edges?.reduce<ProductOption[]>(
(arr, edge) => {
if (edge?.node.__typename === 'MultipleChoiceOption') {
arr.push({
displayName: edge.node.displayName.toLowerCase(),
values: edge.node.values.edges?.map((edge) => edge?.node),
})
}
return arr
},
[]
)
return options
}
// Finds a variant in the product that matches the selected options
export function getCurrentVariant(product: ProductNode, opts: SelectedOptions) {
const variant = product.variants.edges?.find((edge) => {
const { node } = edge ?? {}
return Object.entries(opts).every(([key, value]) =>
node?.productOptions.edges?.find((edge) => {
if (
edge?.node.__typename === 'MultipleChoiceOption' &&
edge.node.displayName.toLowerCase() === key
) {
return edge.node.values.edges?.find(
(valueEdge) => valueEdge?.node.label === value
)
}
})
)
})
return variant
}