Skip to content

Commit

Permalink
feat: add customizable fetch function to ApiClientOptions (#655)
Browse files Browse the repository at this point in the history
  • Loading branch information
IKatsuba authored Nov 9, 2024
1 parent 84614d9 commit 21ac2ed
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/core/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,12 @@ export interface ApiClientOptions {
NonNullable<Parameters<typeof fetch>[1]>,
"method" | "headers" | "body"
>;

/**
* `fetch` function to use for making HTTP requests. Default: `node-fetch` in Node.js, `fetch` in Deno.
*/
fetch?: typeof fetch;

/**
* When the network connection is unreliable and some API requests fail
* because of that, grammY will throw errors that tell you exactly which
Expand All @@ -222,6 +228,8 @@ export interface ApiClientOptions {
class ApiClient<R extends RawApi> {
private readonly options: Required<ApiClientOptions>;

private readonly fetch: typeof fetch;

private hasUsedWebhookReply = false;

readonly installedTransformers: Transformer<R>[] = [];
Expand All @@ -244,7 +252,9 @@ class ApiClient<R extends RawApi> {
},
canUseWebhookReply: options.canUseWebhookReply ?? (() => false),
sensitiveLogs: options.sensitiveLogs ?? false,
fetch: options.fetch ?? fetch,
};
this.fetch = this.options.fetch;
if (this.options.apiRoot.endsWith("/")) {
throw new Error(
`Remove the trailing '/' from the 'apiRoot' option (use '${
Expand Down Expand Up @@ -297,7 +307,7 @@ class ApiClient<R extends RawApi> {
const sig = controller.signal;
const options = { ...opts.baseFetchConfig, signal: sig, ...config };
// Perform fetch call, and handle networking errors
const successPromise = fetch(
const successPromise = this.fetch(
url instanceof URL ? url.href : url,
options,
).catch(toHttpError(method, opts.sensitiveLogs));
Expand Down

0 comments on commit 21ac2ed

Please sign in to comment.