mirror of
https://github.com/vercel/commerce.git
synced 2025-05-17 15:06:59 +00:00
45 lines
940 B
TypeScript
45 lines
940 B
TypeScript
import type { GraphQLFetcher } from '@vercel/commerce/api'
|
|
|
|
import { API_URL } from '../../const'
|
|
import { getError } from '../../utils/handle-fetch-response'
|
|
import { getToken } from '../../utils/index'
|
|
|
|
const fetchGraphqlApi: GraphQLFetcher = async (
|
|
query: string,
|
|
{ variables } = {},
|
|
headers?: HeadersInit
|
|
) => {
|
|
const token = getToken()
|
|
|
|
const res = await fetch(API_URL!, {
|
|
method: 'POST',
|
|
headers: {
|
|
...(token && {
|
|
Authorization: `Bearer ${token}`,
|
|
}),
|
|
...headers,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({
|
|
query,
|
|
variables,
|
|
}),
|
|
})
|
|
|
|
const { data, errors, message, type, status } = await res.json()
|
|
|
|
if (errors) {
|
|
throw getError(
|
|
errors || [
|
|
{
|
|
message: `${type ? `${type}, ` : ''}${message}`,
|
|
},
|
|
],
|
|
status || res.status
|
|
)
|
|
}
|
|
|
|
return { data, res }
|
|
}
|
|
export default fetchGraphqlApi
|