Skip to content

Allow passing custom fetch function #218

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

Merged
merged 3 commits into from
Apr 2, 2021
Merged
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
12 changes: 7 additions & 5 deletions templates/base/http-clients/fetch-http-client.eta
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export interface ApiConfig<SecurityDataType = unknown> {
baseUrl?: string;
baseApiParams?: Omit<RequestParams, "baseUrl" | "cancelToken" | "signal">;
securityWorker?: (securityData: SecurityDataType | null) => Promise<RequestParams | void> | RequestParams | void;
customFetch?: (input: RequestInfo, init?: RequestInit) => Promise<Response>
}

export interface HttpResponse<D extends unknown, E extends unknown = unknown> extends Response {
Expand All @@ -51,6 +52,7 @@ export class HttpClient<SecurityDataType = unknown> {
private securityData: SecurityDataType | null = null;
private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"];
private abortControllers = new Map<CancelToken, AbortController>();
private customFetch = fetch;

private baseApiParams: RequestParams = {
credentials: 'same-origin',
Expand Down Expand Up @@ -118,7 +120,7 @@ export class HttpClient<SecurityDataType = unknown> {
},
};
}

private createAbortSignal = (cancelToken: CancelToken): AbortSignal | undefined => {
if (this.abortControllers.has(cancelToken)) {
const abortController = this.abortControllers.get(cancelToken);
Expand All @@ -127,7 +129,7 @@ export class HttpClient<SecurityDataType = unknown> {
}
return void 0;
}

const abortController = new AbortController();
this.abortControllers.set(cancelToken, abortController);
return abortController.signal;
Expand All @@ -141,7 +143,7 @@ export class HttpClient<SecurityDataType = unknown> {
this.abortControllers.delete(cancelToken);
}
}

public request = async <T = any, E = any>({
body,
secure,
Expand All @@ -158,7 +160,7 @@ export class HttpClient<SecurityDataType = unknown> {
const queryString = query && this.toQueryString(query);
const payloadFormatter = this.contentFormatters[type || ContentType.Json];

return fetch(
return this.customFetch(
`${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`,
{
...requestParams,
Expand Down Expand Up @@ -187,7 +189,7 @@ export class HttpClient<SecurityDataType = unknown> {
r.error = e;
return r;
});

if (cancelToken) {
this.abortControllers.delete(cancelToken);
}
Expand Down