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 #376

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
17 changes: 5 additions & 12 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 @@ -99,9 +100,7 @@ export function createFetch(globalOptions: CreateFetchOptions = {}): $Fetch {
// Uppercase method name
context.options.method = context.options.method?.toUpperCase();

if (context.options.onRequest) {
await context.options.onRequest(context);
}
await callInterceptors(context, "onRequest");

if (typeof context.request === "string") {
if (context.options.baseURL) {
Expand Down Expand Up @@ -163,9 +162,7 @@ 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");
return await onError(context);
}

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

if (context.options.onResponse) {
await context.options.onResponse(context as any);
}
await callInterceptors(context, "onResponse");

if (
!context.options.ignoreResponseError &&
context.response.status >= 400 &&
context.response.status < 600
) {
if (context.options.onResponseError) {
await context.options.onResponseError(context as any);
}
await callInterceptors(context, "onResponseError");
return await onError(context);
}

Expand Down
28 changes: 18 additions & 10 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,14 @@ export interface FetchContext<T = any, R extends ResponseType = ResponseType> {
error?: Error;
}

// --------------------------
// Interceptor
// --------------------------
export type InterceptorCb<T> = (context: T) => Promise<void> | void;
export type Interceptor<T> =
| InterceptorCb<T>
| { enforce: "default" | "pre" | "post"; handler: InterceptorCb<T> };

// --------------------------
// Options
// --------------------------
Expand Down Expand Up @@ -57,16 +65,14 @@ 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?: Arrayable<Interceptor<FetchContext>>;
onRequestError?: Arrayable<Interceptor<FetchContext & { error: Error }>>;
onResponse?: Arrayable<
Interceptor<FetchContext & { response: FetchResponse<R> }>
>;
onResponseError?: Arrayable<
Interceptor<FetchContext & { response: FetchResponse<R> }>
>;
}

export interface CreateFetchOptions {
Expand Down Expand Up @@ -130,3 +136,5 @@ export type FetchRequest = RequestInfo;
export interface SearchParameters {
[key: string]: any;
}

export type Arrayable<T> = T[] | T;
62 changes: 59 additions & 3 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,18 @@
import type { FetchOptions, ResponseType } from "./types";
import type {
Arrayable,
FetchContext,
FetchOptions,
Interceptor,
InterceptorCb,
ResponseType,
} from "./types";

const interceptorNames = [
"onRequest",
"onResponse",
"onRequestError",
"onResponseError",
] as const;

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

// Merging of fetch option objects.
export function mergeFetchOptions(
input: FetchOptions | undefined,
defaults: FetchOptions | undefined,
input?: FetchOptions,
defaults?: FetchOptions,
Headers = globalThis.Headers
): FetchOptions {
const interceptors: Pick<FetchOptions, (typeof interceptorNames)[number]> =
{};

for (const key of interceptorNames) {
if (input?.[key] || defaults?.[key]) {
interceptors[key] = mergeInterceptors(defaults?.[key], input?.[key]);
}
}

const merged: FetchOptions = {
...defaults,
...input,
...interceptors,
};

// Merge params and query
Expand All @@ -99,3 +123,35 @@ export function mergeFetchOptions(

return merged;
}

function mergeInterceptors(
defaults?: Arrayable<Interceptor<any>>,
input?: Arrayable<Interceptor<any>>
): InterceptorCb<any>[] {
return [
...(defaults ? [defaults].flat() : []),
...(input ? [input].flat() : []),
]
.sort((a: any, b: any) => {
if (a?.enforce === "pre" || b?.enforce === "post") {
return -1;
}
if (b?.enforce === "pre" || a?.enforce === "post") {
return 1;
}
return 0;
})
.map((item) => (typeof item === "object" ? item.handler : item));
}

export async function callInterceptors(
ctx: FetchContext,
name: (typeof interceptorNames)[number]
) {
if (!ctx.options[name]) {
return;
}
for (const interceptor of ctx.options[name] as InterceptorCb<any>[]) {
await interceptor(ctx);
}
}
76 changes: 76 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -358,4 +358,80 @@ describe("ofetch", () => {

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

describe.each<{ interceptors: any; expected: string }>([
{
interceptors: [{ data: "_a" }, { data: "_b" }, { data: "_c" }],
expected: "_a_b_c",
},
{
interceptors: [
{ data: "_a" },
{ enforce: "pre", data: "_b" },
{ enforce: "default", data: "_c" },
],
expected: "_b_a_c",
},
{
interceptors: [
{ enforce: "post", data: "_a" },
{ data: "_b" },
{ enforce: "pre", data: "_c" },
],
expected: "_c_b_a",
},
])(
"interceptors must run in the correct order: $expected",
({ interceptors, expected }) => {
it.each([
{
name: "onRequest",
url: "ok",
},
{
name: "onResponse",
url: "ok",
},
{
name: "onRequestError",
url: "ok",
abort: true,
},
{
name: "onResponseError",
url: "/403",
},
])("$name", async ({ name, url, abort }) => {
let res = "";
const controller = new AbortController();
const _customFetch = $fetch.create({
[name]: [
{
enforce: interceptors[0].enforce,
handler: () => (res += interceptors[0].data),
},
],
signal: controller.signal,
});

if (abort) {
controller.abort();
}

await _customFetch(getURL(url), {
[name]: [
{
enforce: interceptors[1].enforce,
handler: () => (res += interceptors[1].data),
},
{
enforce: interceptors[2].enforce,
handler: () => (res += interceptors[2].data),
},
],
}).catch(() => {});
expect(res).to.eq(expected);
});
}
);
});