diff --git a/framework/local/api/index.ts b/framework/local/api/index.ts index 0b1e4d417..9f403d2b3 100644 --- a/framework/local/api/index.ts +++ b/framework/local/api/index.ts @@ -1,6 +1,6 @@ -import type { APIProvider, CommerceAPIConfig } from '@commerce/api' -import { CommerceAPI, getCommerceApi as commerceApi } from '@commerce/api' -import fetcher from './utils/fetch-local' +import type { CommerceAPI, CommerceAPIConfig } from '@commerce/api' +import { getCommerceApi as commerceApi } from '@commerce/api' +import createFetcher from './utils/fetch-local' import getAllPages from './operations/get-all-pages' import getPage from './operations/get-page' @@ -17,7 +17,7 @@ const config: LocalConfig = { cartCookie: '', customerCookie: '', cartCookieMaxAge: 2592000, - fetch: fetcher, + fetch: createFetcher(() => getCommerceApi().getConfig()), } const operations = { diff --git a/framework/local/api/utils/fetch-local.ts b/framework/local/api/utils/fetch-local.ts index ec4ac5e5d..aa85cf27b 100644 --- a/framework/local/api/utils/fetch-local.ts +++ b/framework/local/api/utils/fetch-local.ts @@ -1,36 +1,34 @@ import { FetcherError } from '@commerce/utils/errors' import type { GraphQLFetcher } from '@commerce/api' -import { getCommerceApi } from '../index' +import type { LocalConfig } from '../index' import fetch from './fetch' -const fetchGraphqlApi: GraphQLFetcher = async ( - query: string, - { variables, preview } = {}, - fetchOptions -) => { - const config = getCommerceApi().getConfig() - const res = await fetch(config.commerceUrl, { - ...fetchOptions, - method: 'POST', - headers: { - ...fetchOptions?.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 for API' }], - status: res.status, +const fetchGraphqlApi: (getConfig: () => LocalConfig) => GraphQLFetcher = + (getConfig) => + async (query: string, { variables, preview } = {}, fetchOptions) => { + const config = getConfig() + const res = await fetch(config.commerceUrl, { + ...fetchOptions, + method: 'POST', + headers: { + ...fetchOptions?.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 for API' }], + status: res.status, + }) + } + + return { data: json.data, res } } - return { data: json.data, res } -} - export default fetchGraphqlApi