Normalizing Cart Responses

This commit is contained in:
Belen Curcio
2021-01-12 16:59:07 -03:00
parent 287e690495
commit fc34856e50
8 changed files with 54 additions and 30 deletions

View File

@@ -2,6 +2,7 @@ import type { HookFetcher } from '@commerce/utils/types'
import type { SwrOptions } from '@commerce/utils/use-data'
import useCommerceCart, { CartInput } from '@commerce/cart/use-cart'
import type { Cart } from '../api/cart'
import { normalizeCart } from '../lib/normalize'
const defaultOpts = {
url: '/api/bigcommerce/cart',
@@ -39,7 +40,7 @@ export function extendHook(
set: (x) => x,
})
return response
return normalizeCart(response)
}
useCart.extend = extendHook

View File

@@ -1,6 +1,6 @@
import { Product as BCProduct } from '@framework/schema'
function productOptionNormalize({
function normalizeProductOption({
node: {
entityId,
values: { edges },
@@ -9,7 +9,7 @@ function productOptionNormalize({
}: any) {
return {
id: entityId,
values: edges.map(({ node }: any) => node),
values: edges?.map(({ node }: any) => node),
...rest,
}
}
@@ -45,16 +45,18 @@ export function normalizeProduct(productNode: BCProduct): Product {
? variants.edges.map(
({ node: { entityId, productOptions, ...rest } }: any) => ({
id: entityId,
options: productOptions.edges.map(productOptionNormalize),
options: productOptions?.edges
? productOptions.edges.map(normalizeProductOption)
: [],
...rest,
})
)
: [],
options: productOptions.edges
? productOptions.edges.map(productOptionNormalize)
? productOptions?.edges.map(normalizeProductOption)
: [],
brand: {
id: brand?.entityId,
id: brand?.entityId ? brand?.entityId : null,
...brand,
},
price: {
@@ -64,3 +66,13 @@ export function normalizeProduct(productNode: BCProduct): Product {
...rest,
}
}
export function normalizeCart({ data, ...rest }: any) {
return {
...rest,
data: {
products: data?.line_items?.physical_items ?? [],
...data,
},
}
}

View File

@@ -9,7 +9,7 @@ export type CartResponse<Result> = responseInterface<Result, Error> & {
}
export type CartInput = {
cartId: string | undefined
cartId: Cart['id']
}
export default function useCart<Result>(

View File

@@ -42,7 +42,10 @@ interface ProductPrice {
}
interface Cart extends Entity {
id: string
id: string | undefined
currency: { code: string }
taxIncluded?: boolean
totalAmmount: number | string
products: Pick<Product, 'id' | 'name' | 'prices'>[]
}