commerce/packages/bigcommerce/src/api/utils/fetch-graphql-api.ts
Catalin Pinte c75b0fc001
Dynamic API routes (#836)
* Add dynamic API endpoints

* Add missing dependency

* Update api handlers

* Updates

* Fix build errors

* Update package.json

* Add checkout endpoint parser & update errors

* Update tsconfig.json

* Update cart.ts

* Update parser

* Update errors.ts

* Update errors.ts

* Move to Edge runtime

* Revert to local

* Fix switchable runtimes

* Make nodejs default runtime

* Update pnpm-lock.yaml

* Update handlers

* Fix build errors

* Change headers
2022-10-30 13:41:21 -05:00

40 lines
1.0 KiB
TypeScript

import { FetcherError } from '@vercel/commerce/utils/errors'
import type { GraphQLFetcher } from '@vercel/commerce/api'
import type { BigcommerceConfig } from '../index'
const fetchGraphqlApi: (getConfig: () => BigcommerceConfig) => GraphQLFetcher =
(getConfig) =>
async (
query: string,
{ variables, preview } = {},
options: { headers?: HeadersInit } = {}
): Promise<any> => {
// log.warn(query)
const config = getConfig()
const res = await fetch(config.commerceUrl + (preview ? '/preview' : ''), {
method: 'POST',
headers: {
Authorization: `Bearer ${config.apiToken}`,
...options.headers,
'Content-Type': 'application/json',
},
body: JSON.stringify({
query,
variables,
}),
})
const json = await res.json()
if (json.errors) {
throw new FetcherError({
errors: json.errors ?? [{ message: 'Failed to fetch Bigcommerce API' }],
status: res.status,
})
}
return { data: json.data, res }
}
export default fetchGraphqlApi