mirror of
https://github.com/vercel/commerce.git
synced 2025-07-04 12:11:22 +00:00
* folder and env setup * codegen.json headers removed * use-cart code flow updated * use-cart code flow updated * Implemented get-cart functionality * removed unused file * getAnonymousShopperToken function added * normalization mapping updated * PR points resolved * Anonymous shopper token query added * getAnonymousShopperToken function added * Anonymous shopper token query added Co-authored-by: Chandradeepta <43542673+Chandradeepta@users.noreply.github.com>
69 lines
1.8 KiB
TypeScript
69 lines
1.8 KiB
TypeScript
import type { RequestInit, Response } from '@vercel/fetch'
|
|
import type { KiboCommerceConfig } from '../index'
|
|
import fetch from './fetch'
|
|
|
|
const fetchStoreApi = <T>(getConfig: () => KiboCommerceConfig) => async (
|
|
endpoint: string,
|
|
options?: RequestInit
|
|
): Promise<T> => {
|
|
const config = getConfig()
|
|
let res: Response
|
|
try {
|
|
res = await fetch(config.apiHost + endpoint, {
|
|
...options,
|
|
headers: {
|
|
...options?.headers,
|
|
'Content-Type': 'application/json',
|
|
Authorization: `Bearer ${config.apiToken}`,
|
|
},
|
|
})
|
|
} catch (error) {
|
|
throw new Error(`Fetch to Kibocommerce failed: ${error.message}`)
|
|
}
|
|
|
|
const contentType = res.headers.get('Content-Type')
|
|
const isJSON = contentType?.includes('application/json')
|
|
|
|
if (!res.ok) {
|
|
const data = isJSON ? await res.json() : await getTextOrNull(res)
|
|
console.log('-----------anon-----------', data)
|
|
const headers = getRawHeaders(res)
|
|
const msg = `Kibo Commerce API error (${
|
|
res.status
|
|
}) \nHeaders: ${JSON.stringify(headers, null, 2)}\n${
|
|
typeof data === 'string' ? data : JSON.stringify(data, null, 2)
|
|
}`
|
|
|
|
// throw new BigcommerceApiError(msg, res, data)
|
|
}
|
|
|
|
// if (res.status !== 204 && !isJSON) {
|
|
// throw new BigcommerceApiError(
|
|
// `Fetch to Bigcommerce API failed, expected JSON content but found: ${contentType}`,
|
|
// res
|
|
// )
|
|
// }
|
|
|
|
// If something was removed, the response will be empty
|
|
return res.status === 200 && (await res.json())
|
|
}
|
|
export default fetchStoreApi
|
|
|
|
function getRawHeaders(res: Response) {
|
|
const headers: { [key: string]: string } = {}
|
|
|
|
res.headers.forEach((value, key) => {
|
|
headers[key] = value
|
|
})
|
|
|
|
return headers
|
|
}
|
|
|
|
function getTextOrNull(res: Response) {
|
|
try {
|
|
return res.text()
|
|
} catch (err) {
|
|
return null
|
|
}
|
|
}
|