4
0
forked from crowetic/commerce
commerce/lib/bigcommerce/api/utils/fetch-graphql-api.ts
2020-10-03 16:24:12 -05:00

28 lines
705 B
TypeScript

import { CommerceAPIFetchOptions } from 'lib/commerce/api'
import { getConfig } from '..'
export default async function fetchGraphqlApi<Q, V = any>(
query: string,
{ variables, preview }: CommerceAPIFetchOptions<V> = {}
): Promise<Q> {
const config = getConfig()
const res = await fetch(config.commerceUrl + (preview ? '/preview' : ''), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${config.apiToken}`,
},
body: JSON.stringify({
query,
variables,
}),
})
const json = await res.json()
if (json.errors) {
console.error(json.errors)
throw new Error('Failed to fetch API')
}
return json.data
}