Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: have both local and global interceptors #357

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion playground/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,21 @@
import { $fetch } from "../src/node";

const myFetch = $fetch.create({
onResponse: {
strategy: "after",
handler(ctx, data) {
return 'global: ' + data
},
}
})

async function main() {
const r = await myFetch<string>("http://httpstat.us/200", {
onResponse(ctx, data) {
return 'local -> ' + data
}
});
// const r = await $fetch<string>('http://google.com/404')
const r = await $fetch<string>("http://httpstat.us/500");
// const r = await $fetch<string>('http://httpstat/500')
// eslint-disable-next-line no-console
console.log(r);
Expand Down
45 changes: 34 additions & 11 deletions src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
isJSONSerializable,
detectResponseType,
mergeFetchOptions,
callInterceptors,
} from "./utils";
import type {
CreateFetchOptions,
Expand Down Expand Up @@ -89,19 +90,19 @@ export function createFetch(globalOptions: CreateFetchOptions = {}): $Fetch {
_request,
_options = {}
) {
const { onRequest, onRequestError, onResponse, onResponseError, ...restOptions } = _options

const context: FetchContext = {
request: _request,
options: mergeFetchOptions(_options, globalOptions.defaults, Headers),
options: mergeFetchOptions(restOptions, globalOptions.defaults, Headers),
response: undefined,
error: undefined,
};

// Uppercase method name
context.options.method = context.options.method?.toUpperCase();

if (context.options.onRequest) {
await context.options.onRequest(context);
}
await callInterceptors(context, onRequest, globalOptions.defaults?.onRequest)

if (typeof context.request === "string") {
if (context.options.baseURL) {
Expand Down Expand Up @@ -163,9 +164,14 @@ export function createFetch(globalOptions: CreateFetchOptions = {}): $Fetch {
);
} catch (error) {
context.error = error as Error;
if (context.options.onRequestError) {
await context.options.onRequestError(context as any);
}

await callInterceptors(
context,
onRequestError,
globalOptions.defaults?.onRequestError,
context.error
)

return await onError(context);
}

Expand Down Expand Up @@ -198,18 +204,33 @@ export function createFetch(globalOptions: CreateFetchOptions = {}): $Fetch {
}
}

if (context.options.onResponse) {
await context.options.onResponse(context as any);
let _result = await callInterceptors(
context,
onResponse,
globalOptions.defaults?.onResponse,
context.response._data
)

if (_result !== undefined) {
context.response._data = _result
}

if (
!context.options.ignoreResponseError &&
context.response.status >= 400 &&
context.response.status < 600
) {
if (context.options.onResponseError) {
await context.options.onResponseError(context as any);
_result = await callInterceptors(
context,
onResponseError,
globalOptions.defaults?.onResponseError,
context.response._data
)

if (_result !== undefined) {
context.response._data = _result
}

return await onError(context);
}

Expand Down Expand Up @@ -237,3 +258,5 @@ export function createFetch(globalOptions: CreateFetchOptions = {}): $Fetch {

return $fetch;
}


38 changes: 26 additions & 12 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export interface $Fetch {
options?: FetchOptions<R>
): Promise<FetchResponse<MappedResponseType<R, T>>>;
native: Fetch;
create(defaults: FetchOptions): $Fetch;
create(defaults: GlobalFetchOptions): $Fetch;
}

// --------------------------
Expand All @@ -27,6 +27,18 @@ export interface FetchContext<T = any, R extends ResponseType = ResponseType> {
error?: Error;
}

// --------------------------
// Interceptor
// --------------------------

export type InterceptorFn<T> = (context: T, data: any) => Promise<any> | any
export type Interceptor<T> = InterceptorFn<T> | {
strategy: 'overwrite' | "manual" | "before" | "after",
handler: InterceptorFn<T>
}

export type OmitInterceptors<T> = Omit<T, "onRequest" | "onRequestError" | "onResponse" | "onResponseError">;

// --------------------------
// Options
// --------------------------
Expand Down Expand Up @@ -57,21 +69,23 @@ export interface FetchOptions<R extends ResponseType = ResponseType>
/** Default is [408, 409, 425, 429, 500, 502, 503, 504] */
retryStatusCodes?: number[];

onRequest?(context: FetchContext): Promise<void> | void;
onRequestError?(
context: FetchContext & { error: Error }
): Promise<void> | void;
onResponse?(
context: FetchContext & { response: FetchResponse<R> }
): Promise<void> | void;
onResponseError?(
context: FetchContext & { response: FetchResponse<R> }
): Promise<void> | void;
onRequest?: InterceptorFn<FetchContext>
onRequestError?: InterceptorFn<FetchContext & { error: Error }>
onResponse?: InterceptorFn<FetchContext & { response: FetchResponse<R> }>
onResponseError?: InterceptorFn<FetchContext & { response: FetchResponse<R> }>
}

export interface GlobalFetchOptions<R extends ResponseType = ResponseType>
extends OmitInterceptors<FetchOptions<R>> {
onRequest?: Interceptor<FetchContext>
onRequestError?: Interceptor<FetchContext & { error: Error }>
onResponse?: Interceptor<FetchContext & { response: FetchResponse<R> }>
onResponseError?: Interceptor<FetchContext & { response: FetchResponse<R> }>
}

export interface CreateFetchOptions {
// eslint-disable-next-line no-use-before-define
defaults?: FetchOptions;
defaults?: GlobalFetchOptions;
fetch?: Fetch;
Headers?: typeof Headers;
AbortController?: typeof AbortController;
Expand Down
29 changes: 26 additions & 3 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { FetchOptions, ResponseType } from "./types";
import type { FetchContext, FetchOptions, Interceptor, InterceptorFn, OmitInterceptors, ResponseType } from "./types";

const payloadMethods = new Set(
Object.freeze(["PATCH", "POST", "PUT", "DELETE"])
Expand Down Expand Up @@ -66,8 +66,8 @@ export function detectResponseType(_contentType = ""): ResponseType {

// Merging of fetch option objects.
export function mergeFetchOptions(
input: FetchOptions | undefined,
defaults: FetchOptions | undefined,
input: OmitInterceptors<FetchOptions> | undefined,
defaults: OmitInterceptors<FetchOptions> | undefined,
Headers = globalThis.Headers
): FetchOptions {
const merged: FetchOptions = {
Expand Down Expand Up @@ -99,3 +99,26 @@ export function mergeFetchOptions(

return merged;
}

export async function callInterceptors(
ctx: FetchContext,
cb?: InterceptorFn<any>,
globalCb?: Interceptor<any>,
data?: any
) {
if (typeof globalCb === "object") {
const { strategy, handler } = globalCb

if (!cb || strategy === "manual") {
return handler(ctx, data)
}
if (strategy === "before") {
return handler(ctx, await cb(ctx, data))
}
if (strategy === "after") {
return cb(ctx, await handler(ctx, data))
}
}

return cb ? cb(ctx, data) : (globalCb ? (globalCb as InterceptorFn<any>)(ctx, data) : data)
}
90 changes: 90 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -358,4 +358,94 @@ describe("ofetch", () => {

expect(path).to.eq("?b=2&c=3&a=1");
});

describe.each<{ strategy: "overwrite" | "manual" | "before" | "after", expected: string}>([
{ strategy: 'overwrite', expected: '_local' },
{ strategy: 'after', expected: '_global_local' },
{ strategy: 'before', expected: '_local_global' },
{ strategy: 'manual', expected: '_global' }
])('interceptors $strategy strategy', ({ strategy, expected }) => {
it(`onRequest`, async () => {
let res = ''
const _customFetch = $fetch.create({
onRequest: {
strategy,
handler(ctx, data) {
res = (data || '') + '_global';
return res
},
}
});

await _customFetch(getURL("ok"), {
onRequest(ctx, data) {
res = (data || '') + '_local';
return res
}
});
expect(res).to.eq(expected);
})

it(`onRequestError`, async () => {
let res = ''
const _customFetch = $fetch.create({
onRequestError: {
strategy,
handler(ctx, data) {
res = (data instanceof TypeError ? data.name : data) + '_global';
return res
},
},
retry: false
});

await _customFetch('/nonexistent', {
onRequestError(ctx, data) {
res = (data instanceof TypeError ? data.name : data) + '_local';
return res
}
}).catch(() => {});
expect(res).to.eq('TypeError' + expected);
})

it(`onResponse`, async () => {
const _customFetch = $fetch.create({
onResponse: {
strategy,
handler(ctx, data) {
return data + '_global';
},
}
});

const res = await _customFetch(getURL("ok"), {
onResponse(ctx, data) {
return data + '_local';
}
});
expect(res).to.eq('ok' + expected);
})

it(`onResponseError`, async () => {
const _customFetch = $fetch.create({
onResponseError: {
strategy,
handler(ctx, data) {
return {
statusCode: data.statusCode + '_global'
}
},
},
});

const res = await _customFetch(getURL("403"), {
onResponseError(ctx, data) {
return {
statusCode: data.statusCode + '_local'
}
}
}).catch(({ data }) => data);
expect(res.statusCode).to.eq('403' + expected);
})
})
});