Skip to content

Commit

Permalink
refactor: init custom fetch in resolveFetch
Browse files Browse the repository at this point in the history
  • Loading branch information
BartoszJarocki committed Feb 6, 2024
1 parent 141cd81 commit 22c4efe
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 10 deletions.
2 changes: 1 addition & 1 deletion src/lib/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,5 @@ export const DEFAULT_FETCH_OPTIONS: FetchOptions = {

export const DEFAULT_OPTIONS: DeepgramClientOptions = {
global: DEFAULT_GLOBAL_OPTIONS,
fetchOptions: DEFAULT_FETCH_OPTIONS,
fetch: DEFAULT_FETCH_OPTIONS,
};
10 changes: 6 additions & 4 deletions src/lib/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,20 @@ import crossFetch from "cross-fetch";
import { resolveHeadersConstructor } from "./helpers";
import type { Fetch } from "./types/Fetch";

export const resolveFetch = (): Fetch => {
export const resolveFetch = (customFetch?: Fetch): Fetch => {
let _fetch: Fetch;
if (typeof fetch === "undefined") {
if (customFetch) {
_fetch = customFetch;
} else if (typeof fetch === "undefined") {
_fetch = crossFetch as unknown as Fetch;
} else {
_fetch = fetch;
}
return (...args) => _fetch(...args);
};

export const fetchWithAuth = (apiKey: string): Fetch => {
const fetch = resolveFetch();
export const fetchWithAuth = (apiKey: string, customFetch?: Fetch): Fetch => {
const fetch = resolveFetch(customFetch);
const HeadersConstructor = resolveHeadersConstructor();

return async (input, init) => {
Expand Down
4 changes: 2 additions & 2 deletions src/lib/types/DeepgramClientOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ export interface DeepgramClientOptions {
*/
url?: string;
};
fetchOptions?: FetchOptions;
fetch?: Fetch;
fetch?: FetchOptions;
customFetch?: Fetch;
restProxy?: {
url: null | string;
};
Expand Down
6 changes: 3 additions & 3 deletions src/packages/AbstractRestfulClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export abstract class AbstractRestfulClient extends AbstractClient {
);
}

this.fetch = options.fetch ? options.fetch : fetchWithAuth(this.key);
this.fetch = fetchWithAuth(this.key, options.customFetch);
}

protected _getErrorMessage(err: any): string {
Expand Down Expand Up @@ -49,9 +49,9 @@ export abstract class AbstractRestfulClient extends AbstractClient {
body?: string | Buffer | Readable
) {
const params: { [k: string]: any } = {
...this.options?.fetchOptions,
...this.options?.fetch,
method,
headers: { ...this.options?.fetchOptions?.headers, ...headers } || {},
headers: { ...this.options?.fetch?.headers, ...headers } || {},
};

if (method === "GET") {
Expand Down

0 comments on commit 22c4efe

Please sign in to comment.