Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 17 additions & 10 deletions packages/js/src/fetchClient.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fetchRetry from "fetch-retry";
import { parseLimitFromResponse, Limit, LimitType } from "./limit.js";
import fetchRetry from 'fetch-retry';
import { parseLimitFromResponse, Limit, LimitType } from './limit.js';

export class FetchClient {
constructor(public config: { headers: HeadersInit; baseUrl: string; timeout: number }) {}
Expand Down Expand Up @@ -29,7 +29,7 @@ export class FetchClient {
method,
body: init.body ? init.body : undefined,
signal: AbortSignal.timeout(timeout),
cache: "no-store",
cache: 'no-store',
});

if (resp.status === 204) {
Expand All @@ -39,29 +39,36 @@ export class FetchClient {

return Promise.reject(new AxiomTooManyRequestsError(limit));
} else if (resp.status === 401) {
return Promise.reject(new Error("Forbidden"));
return Promise.reject(new Error('Forbidden'));
} else if (resp.status >= 400) {
const payload = (await resp.json()) as { message: string };
const payload = (await resp.json().catch(() => null)) as { message: string } | null;
if (!payload) {
const tryText = await resp.text().catch(() => null);
if (!tryText || tryText.length === 0) {
return Promise.reject(new Error(`Unknown ${resp.status} error`));
}
return Promise.reject(new Error(tryText));
}
return Promise.reject(new Error(payload.message));
}

return (await resp.json()) as T;
}

post<T>(url: string, init: RequestInit = {}, searchParams: any = {}, timeout = this.config.timeout): Promise<T> {
return this.doReq<T>(url, "POST", init, searchParams, timeout);
return this.doReq<T>(url, 'POST', init, searchParams, timeout);
}

get<T>(url: string, init: RequestInit = {}, searchParams: any = {}, timeout = this.config.timeout): Promise<T> {
return this.doReq<T>(url, "GET", init, searchParams, timeout);
return this.doReq<T>(url, 'GET', init, searchParams, timeout);
}

put<T>(url: string, init: RequestInit = {}, searchParams: any = {}, timeout = this.config.timeout): Promise<T> {
return this.doReq<T>(url, "PUT", init, searchParams, timeout);
return this.doReq<T>(url, 'PUT', init, searchParams, timeout);
}

delete<T>(url: string, init: RequestInit = {}, searchParams: any = {}, timeout = this.config.timeout): Promise<T> {
return this.doReq<T>(url, "DELETE", init, searchParams, timeout);
return this.doReq<T>(url, 'DELETE', init, searchParams, timeout);
}

_prepareSearchParams = (searchParams: { [key: string]: string }) => {
Expand All @@ -80,7 +87,7 @@ export class FetchClient {
}

export class AxiomTooManyRequestsError extends Error {
public message: string = "";
public message: string = '';

constructor(
public limit: Limit,
Expand Down
Loading