shopify: changes

This commit is contained in:
Bel Curcio
2021-02-25 07:48:14 -03:00
parent e10d50c55a
commit 3b386e3d55
5 changed files with 88 additions and 34 deletions

View File

@@ -3,14 +3,11 @@ import fetchGraphqlApi from './utils/fetch-graphql-api'
export interface ShopifyConfig extends CommerceAPIConfig {}
const API_URL =
process.env.SHOPIFY_STORE_DOMAIN ||
process.env.NEXT_PUBLIC_SHOPIFY_STORE_DOMAIN
const API_TOKEN =
process.env.SHOPIFY_STOREFRONT_ACCESS_TOKEN ||
process.env.NEXT_PUBLIC_SHOPIFY_STOREFRONT_ACCESS_TOKEN
const API_URL = process.env.SHOPIFY_STORE_DOMAIN
const API_TOKEN = process.env.SHOPIFY_STOREFRONT_ACCESS_TOKEN
if (!API_URL) {
console.log(process.env)
throw new Error(
`The environment variable SHOPIFY_STORE_DOMAIN is missing and it's required to access your store`
)

View File

@@ -0,0 +1,51 @@
import { FetcherError } from '@commerce/utils/errors'
import type { Fetcher } from '@commerce/utils/types'
async function getText(res: Response) {
try {
return (await res.text()) || res.statusText
} catch (error) {
return res.statusText
}
}
async function getError(res: Response) {
if (res.headers.get('Content-Type')?.includes('application/json')) {
const data = await res.json()
return new FetcherError({ errors: data.errors, status: res.status })
}
return new FetcherError({ message: await getText(res), status: res.status })
}
const fetcher: Fetcher = async ({
url,
query,
method = 'POST',
variables,
body: bodyObj,
}) => {
// const config = getConfig()
// url = `https://${process.env.SHOPIFY_STORE_DOMAIN}/api/2021-01/graphql.json`
const hasBody = Boolean(variables || bodyObj)
const body = hasBody
? JSON.stringify(variables ? { query, variables } : bodyObj)
: undefined
const headers = hasBody
? {
'X-Shopify-Storefront-Access-Token': config.apiToken,
'Content-Type': 'application/json',
}
: undefined
const res = await fetch(url!, { method, body, headers })
if (res.ok) {
const { data } = await res.json()
return data
}
throw await getError(res)
}
export default fetcher