From 9062048a809f45228b824075f5c9f55223ea4b96 Mon Sep 17 00:00:00 2001 From: Igor Katsuba Date: Tue, 12 Nov 2024 02:59:38 +0200 Subject: [PATCH] fix: implement custom fetch handling in ApiClient for Cloudflare compatibility (#660) --- src/core/client.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/core/client.ts b/src/core/client.ts index f707a593..807be506 100644 --- a/src/core/client.ts +++ b/src/core/client.ts @@ -241,6 +241,13 @@ class ApiClient { ) { const apiRoot = options.apiRoot ?? "https://api.telegram.org"; const environment = options.environment ?? "prod"; + + // In an ideal world, `fetch` is independent of the context being called, + // but in a Cloudflare worker, any context other than global throws an error. + // That is why we need to call custom fetch or fetch without context. + const { fetch: customFetch } = options; + const fetchFn = customFetch ?? fetch; + this.options = { apiRoot, environment, @@ -252,7 +259,9 @@ class ApiClient { }, canUseWebhookReply: options.canUseWebhookReply ?? (() => false), sensitiveLogs: options.sensitiveLogs ?? false, - fetch: options.fetch ?? fetch, + fetch: + ((...args: Parameters) => + fetchFn(...args)) as typeof fetch, }; this.fetch = this.options.fetch; if (this.options.apiRoot.endsWith("/")) {