Skip to content

Commit

Permalink
fix: Typing of both fetches
Browse files Browse the repository at this point in the history
  • Loading branch information
asafgardin committed Nov 13, 2024
1 parent 50956e2 commit fbb8080
Show file tree
Hide file tree
Showing 7 changed files with 34 additions and 22 deletions.
12 changes: 3 additions & 9 deletions src/APIClient.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { AI21Error } from './errors';
import { VERSION } from './version';

import { RequestOptions, FinalRequestOptions, APIResponseProps, HTTPMethod, Headers } from './types/index.js';
import { RequestOptions, FinalRequestOptions, APIResponseProps, HTTPMethod, Headers, UnifiedResponse } from './types';
import { AI21EnvConfig } from './EnvConfig';
import { handleAPIResponse } from './ResponseHandler';
import { createFetchInstance } from 'envFetch';
Expand Down Expand Up @@ -90,25 +90,19 @@ export abstract class APIClient {
}

private async performRequest(options: FinalRequestOptions): Promise<APIResponseProps> {
const controller = new AbortController();
const url = `${this.baseURL}${options.path}`;

const headers = {
...this.defaultHeaders(options),
...options.headers,
};
const response = await this.fetch.call(url, {
method: options.method,
headers: headers as any,
signal: controller.signal,
body: options.body ? JSON.stringify(options.body) : undefined,
});
const response = await this.fetch.call(url, { ...options, headers });

if (!response.ok) {
throw new AI21Error(`Request failed with status ${response.status}. ${await response.text()}`);
}

return { response, options, controller };
return { response: response as UnifiedResponse, options };
}

protected isRunningInBrowser(): boolean {
Expand Down
5 changes: 3 additions & 2 deletions src/Streaming/Stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { DefaultSSEDecoder } from './SSEDecoder';
import { SSEDecoder } from './SSEDecoder';
import { SSE_DONE_MSG } from './Consts';
import { StreamingDecodeError } from '../errors';
import { UnifiedResponse } from '../types';

function getStreamMessage<T>(chunk: string): T {
try {
Expand All @@ -16,15 +17,15 @@ export class Stream<T> implements AsyncIterableIterator<T> {
private iterator: AsyncIterableIterator<T>;

constructor(
private response: Response,
private response: UnifiedResponse,
decoder?: SSEDecoder,
) {
this.decoder = decoder || new DefaultSSEDecoder();
this.iterator = this.stream();
}

private async *stream(): AsyncIterableIterator<T> {
for await (const chunk of this.decoder.iterLines(this.response)) {
for await (const chunk of this.decoder.iterLines(this.response as Response)) {
if (chunk === SSE_DONE_MSG) break;
yield getStreamMessage(chunk);
}
Expand Down
5 changes: 4 additions & 1 deletion src/fetch/BaseFetch.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { FinalRequestOptions, UnifiedResponse } from "types";


export abstract class Fetch {
abstract call(url: string, options?: RequestInit): Promise<Response>;
abstract call(url: string, options: FinalRequestOptions): Promise<UnifiedResponse>;
}
12 changes: 10 additions & 2 deletions src/fetch/BrowserFetch.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import { FinalRequestOptions, UnifiedResponse } from 'types';
import { Fetch } from './BaseFetch';

export class BrowserFetch extends Fetch {
call(url: string, options?: RequestInit): Promise<Response> {
return fetch(url, options);
call(url: string, options: FinalRequestOptions): Promise<UnifiedResponse> {
const controller = new AbortController();

return fetch(url, {
method: options?.method,
headers: options?.headers as HeadersInit,
body: options.body ? JSON.stringify(options.body) : undefined,
signal: controller.signal,
});
}
}
16 changes: 10 additions & 6 deletions src/fetch/NodeFetch.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
// import { RequestInit as NodeRequestInit } from 'node-fetch';

import { FinalRequestOptions, UnifiedResponse } from "types";
import { Fetch } from "./BaseFetch";

export class NodeFetch extends Fetch {
async call(url: string, options?: RequestInit): Promise<Response> {
const nodeFetch = (await import("node-fetch")).default;
// @ts-ignore
return nodeFetch(url, options);
async call(url: string, options: FinalRequestOptions): Promise<UnifiedResponse> {
const nodeFetchModule = await import("node-fetch");
const nodeFetch = nodeFetchModule.default;

return nodeFetch(url, {
method: options?.method,
headers: options.headers as Record<string, string>,
body: options?.body ? JSON.stringify(options.body) : undefined,
});
}
}
5 changes: 3 additions & 2 deletions src/types/API.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
export type HTTPMethod = 'get' | 'post' | 'put' | 'patch' | 'delete';

export type APIResponseProps = {
response: Response;
response: UnifiedResponse;
options: FinalRequestOptions;
controller: AbortController;
controller?: AbortController;
};

export type RequestOptions<
Expand All @@ -27,3 +27,4 @@ export type FinalRequestOptions = RequestOptions & {

export type DefaultQuery = Record<string, unknown>;
export type Headers = Record<string, string | null | undefined>;
export type UnifiedResponse = Response | import('node-fetch').Response;
1 change: 1 addition & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,5 @@ export {
type HTTPMethod,
type DefaultQuery,
type Headers,
type UnifiedResponse,
} from './API';

0 comments on commit fbb8080

Please sign in to comment.