2020-10-03 06:45:09 -05:00
|
|
|
import { ReactNode } from 'react'
|
2020-09-30 11:44:38 -05:00
|
|
|
import {
|
2020-10-03 06:45:09 -05:00
|
|
|
CommerceConfig,
|
2020-09-30 11:44:38 -05:00
|
|
|
CommerceProvider as CoreCommerceProvider,
|
|
|
|
useCommerce as useCoreCommerce,
|
2020-10-01 20:40:40 -05:00
|
|
|
} from 'lib/commerce'
|
2020-09-30 11:44:38 -05:00
|
|
|
|
|
|
|
async function getText(res: Response) {
|
|
|
|
try {
|
2020-10-01 20:40:40 -05:00
|
|
|
return (await res.text()) || res.statusText
|
2020-09-30 11:44:38 -05:00
|
|
|
} catch (error) {
|
2020-10-01 20:40:40 -05:00
|
|
|
return res.statusText
|
2020-09-30 11:44:38 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async function getError(res: Response) {
|
|
|
|
if (res.headers.get('Content-Type')?.includes('application/json')) {
|
2020-10-01 20:40:40 -05:00
|
|
|
const data = await res.json()
|
|
|
|
return data.errors[0]
|
2020-09-30 11:44:38 -05:00
|
|
|
}
|
2020-10-01 20:40:40 -05:00
|
|
|
return { message: await getText(res) }
|
2020-09-30 11:44:38 -05:00
|
|
|
}
|
|
|
|
|
2020-10-03 06:45:09 -05:00
|
|
|
export const bigcommerceConfig: CommerceConfig = {
|
2020-09-30 11:44:38 -05:00
|
|
|
locale: 'en-us',
|
2020-10-04 13:46:28 -05:00
|
|
|
async fetcher({ url, method = 'GET', variables, body: bodyObj }) {
|
|
|
|
const hasBody = Boolean(variables || bodyObj)
|
|
|
|
const body = hasBody
|
|
|
|
? JSON.stringify(variables ? { variables } : bodyObj)
|
|
|
|
: undefined
|
|
|
|
const headers = hasBody ? { 'Content-Type': 'application/json' } : undefined
|
|
|
|
const res = await fetch(url!, { method, body, headers })
|
2020-10-04 13:12:41 -05:00
|
|
|
|
|
|
|
if (res.ok) {
|
2020-10-04 13:46:28 -05:00
|
|
|
const { data } = await res.json()
|
2020-10-04 19:44:11 -05:00
|
|
|
console.log('DATA', data)
|
2020-10-04 13:46:28 -05:00
|
|
|
return data
|
2020-10-04 13:12:41 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
throw await getError(res)
|
|
|
|
},
|
2020-10-01 20:40:40 -05:00
|
|
|
}
|
2020-09-30 11:44:38 -05:00
|
|
|
|
2020-10-03 06:45:09 -05:00
|
|
|
export type BigcommerceConfig = Partial<CommerceConfig>
|
|
|
|
|
|
|
|
export type BigcommerceProps = {
|
|
|
|
children?: ReactNode
|
2020-10-04 19:46:43 -05:00
|
|
|
locale: string
|
2020-10-04 19:44:11 -05:00
|
|
|
} & BigcommerceConfig
|
2020-10-02 12:59:50 -03:00
|
|
|
|
2020-10-04 19:44:11 -05:00
|
|
|
export function CommerceProvider({ children, ...config }: BigcommerceProps) {
|
2020-09-30 11:44:38 -05:00
|
|
|
return (
|
2020-10-04 19:44:11 -05:00
|
|
|
<CoreCommerceProvider config={{ ...bigcommerceConfig, ...config }}>
|
2020-09-30 11:44:38 -05:00
|
|
|
{children}
|
|
|
|
</CoreCommerceProvider>
|
2020-10-01 20:40:40 -05:00
|
|
|
)
|
2020-09-30 11:44:38 -05:00
|
|
|
}
|
|
|
|
|
2020-10-01 20:40:40 -05:00
|
|
|
export const useCommerce = () => useCoreCommerce()
|