diff --git a/src/Client.ts b/src/Client.ts index f98bde0b..1d4adc05 100644 --- a/src/Client.ts +++ b/src/Client.ts @@ -45,7 +45,7 @@ class Client { ...customOptions } - const fetcherOptions: CreateFetcherConfig = { host: options.host } + const fetcherOptions: CreateFetcherConfig = { host: options.host, beforeRequestFunction: options?.beforeRequestFunction } this.fetcher = options.createFetcher(fetcherOptions) diff --git a/src/Http.ts b/src/Http.ts index fc46e359..e29fe31e 100644 --- a/src/Http.ts +++ b/src/Http.ts @@ -69,13 +69,14 @@ export default class Http { } protected processError(error: Error): SpreeSDKError { - if (error instanceof FetchError) { - if (error.response) { + if ((error as FetchError)?.response) { + const fetchError = (error as FetchError) + if (fetchError.response) { // Error from Spree outside HTTP 2xx codes return this.processSpreeError(error) } - if (error.request) { + if (fetchError.request) { // No response received from Spree return new NoResponseError() } diff --git a/src/fetchers/createAxiosFetcher.ts b/src/fetchers/createAxiosFetcher.ts index 69233092..09c85635 100644 --- a/src/fetchers/createAxiosFetcher.ts +++ b/src/fetchers/createAxiosFetcher.ts @@ -18,6 +18,9 @@ const createAxiosFetcher: CreateFetcher = (fetcherOptions) => { headers: { 'Content-Type': 'application/json' }, paramsSerializer: (params) => objectToQuerystring(params) }) + if (fetcherOptions.beforeRequestFunction){ + fetcherOptions?.beforeRequestFunction(axios) + } return { fetch: async (fetchOptions) => { diff --git a/src/fetchers/createFetchFetcher.ts b/src/fetchers/createFetchFetcher.ts index b927f02d..acbcb03d 100644 --- a/src/fetchers/createFetchFetcher.ts +++ b/src/fetchers/createFetchFetcher.ts @@ -8,6 +8,10 @@ const createCustomizedFetchFetcher: CreateCustomizedFetchFetcher = (fetcherOptio const { host, fetch, requestConstructor } = fetcherOptions + if (fetcherOptions.beforeRequestFunction){ + fetcherOptions?.beforeRequestFunction() + } + return { fetch: async (fetchOptions) => { try { diff --git a/src/interfaces/ClientConfig.ts b/src/interfaces/ClientConfig.ts index e807774f..902ae529 100644 --- a/src/interfaces/ClientConfig.ts +++ b/src/interfaces/ClientConfig.ts @@ -1,4 +1,5 @@ import type { FetchConfig } from './FetchConfig' +import { AxiosInstance } from 'axios' export type Fetcher = { fetch: (options: FetchConfig) => Promise<{ data: any }> @@ -8,10 +9,12 @@ export type CreateFetcher = (options: CreateFetcherConfig) => Fetcher export type CreateFetcherConfig = { host: string + beforeRequestFunction?(axios?: AxiosInstance): any } export type FetcherConfig = { createFetcher: CreateFetcher } + export type IClientConfig = CreateFetcherConfig & FetcherConfig