diff --git a/src/private/runApi.ts b/src/private/runApi.ts index b5195e4..730dcf0 100644 --- a/src/private/runApi.ts +++ b/src/private/runApi.ts @@ -63,8 +63,8 @@ const getUrl = (options: ActionOptions): string => { const shouldUseCache = ({ options, requestType }: Request): boolean => { return Boolean( requestType.kind === 'fetch' && - Boolean(requestType.piece?.list?.length) && - options.cache, + Boolean(requestType.piece?.list?.length) && + options.cache, ) } @@ -107,22 +107,8 @@ const failureAction = ( } } -async function mock(options: ActionOptions): Promise { - await sleep(options.mockTimeout || 0) - const [error, result] = await attempt( - () => options.mockResponse?.() || Promise.resolve(), - ) - if (error) { - return { - ok: false, - text: () => Promise.resolve(error), - } as Response - } - return { - ok: true, - json: () => Promise.resolve(result), - } as Response -} +const mockOrFetch: (options: ActionOptions) => (url: string, conig: RequestInit) => Promise = + (options: ActionOptions) => options.mockFetch ?? fetch async function runApi( request: Request, @@ -144,12 +130,14 @@ async function runApi( : requestType.piece.list return Promise.resolve(result) } - const isMock = typeof options.mockResponse !== 'undefined' + const isMock = typeof options.mockFetch !== 'undefined' options.debugRequests && requestLogger(url, method, {}, isMock) requestAction(request) - const [error, response] = await attempt(() => - options.mockResponse ? mock(options) : fetch(url, config), - ) + + if (options.mockTimeout) { + await sleep(options.mockTimeout) + } + const [error, response] = await attempt(() => mockOrFetch(options)(url, config)) options.debugRequests && responseLogger(url, method, response || error, isMock) if (response?.ok) { diff --git a/src/types.ts b/src/types.ts index 41f808a..306f6a1 100644 --- a/src/types.ts +++ b/src/types.ts @@ -53,7 +53,7 @@ type ProviderOptions = { debugRequests?: boolean handleResponseHeaders?: (t: Response) => void headers?: ((t: HeadersObj) => HeadersObj) | HeadersObj - mockResponse?: () => Promise + mockFetch?: typeof fetch mockTimeout?: number paramsParser?: (t: string) => string paramsUnparser?: (t: string) => string