Skip to content

Commit

Permalink
Merge pull request #257 from tharropoulos/cloudflare-workers
Browse files Browse the repository at this point in the history
Fix Axios adapter binding for Cloudflare Workers environment
  • Loading branch information
jasonbosco authored Jan 17, 2025
2 parents fe4caf5 + 7d0800d commit f640cdd
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions src/Typesense/ApiCall.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import type { AxiosRequestConfig, AxiosResponse, Method } from "axios";
import type {
AxiosAdapter,
AxiosRequestConfig,
AxiosResponse,
Method,
} from "axios";
import axios from "axios";
import { Agent as HTTPAgent } from "http";
import { Agent as HTTPSAgent } from "https";
Expand Down Expand Up @@ -124,6 +129,21 @@ export default class ApiCall {
});
}

private getAdapter(): AxiosAdapter | undefined {
if (!this.configuration.axiosAdapter) return undefined;

if (typeof this.configuration.axiosAdapter === "function")
return this.configuration.axiosAdapter;

const isCloudflareWorkers =
typeof navigator !== "undefined" &&
navigator.userAgent === "Cloudflare-Workers";

return isCloudflareWorkers
? axios.getAdapter(this.configuration.axiosAdapter).bind(globalThis)
: axios.getAdapter(this.configuration.axiosAdapter);
}

async performRequest<T>(
requestType: Method,
endpoint: string,
Expand Down Expand Up @@ -173,7 +193,7 @@ export default class ApiCall {

try {
const requestOptions: AxiosRequestConfig = {
adapter: this.configuration.axiosAdapter,
adapter: this.getAdapter(),
method: requestType,
url: this.uriFor(endpoint, node),
headers: Object.assign(
Expand Down

0 comments on commit f640cdd

Please sign in to comment.