Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Add HttpClient class for making HTTP requests

Kiran Kd08ebf65f146
diff --git a/apps/web/tests/utils/http.ts b/apps/web/tests/utils/http.ts
new file mode 100644
index 0000000000..69dfeb4c4d
--- /dev/null
+++ b/apps/web/tests/utils/http.ts
@@ -0,0 +1,61 @@
+type Request = {
+ path: string;
+ query?: Record<string, string>;
+ body?: unknown;
+ headers?: Record<string, string>;
+ retries?: number;
+};
+
+type HttpClientConfig = {
+ headers?: Record<string, string>;
+ baseUrl: string;
+};
+
+type Response<TResponse> = {
+ data: TResponse;
+ status: number;
+};
+
+export class HttpClient {
+ public readonly baseUrl: string;
+ public readonly headers: Record<string, string>;
+
+ public constructor(config: HttpClientConfig) {
+ this.baseUrl = config.baseUrl.replace(/\/$/, "");
+ this.headers = config.headers ?? {};
+ }
+
+ private async request<TResponse>(
+ method: "GET" | "POST" | "PUT" | "DELETE",
+ req: Request,
+ ): Promise<Response<TResponse>> {
+ const headers = {
+ "Content-Type": "application/json",
+ ...this.headers,
+ ...req.headers,
+ };
+
+ const params = new URLSearchParams(req.query).toString();
+ const url = `${this.baseUrl}${req.path}${params ? `?${params}` : ""}`;
+
+ const response = await fetch(url, {
+ method,
+ headers,
+ keepalive: true,
+ body: JSON.stringify(req.body),
+ });
+
+ const { status } = response;
+ const data = (await response.json()) as TResponse;
+
+ return { data, status };
+ }
+
+ public async get<TResponse>(req: Request) {
+ return await this.request<TResponse>("GET", req);
+ }
+
+ public async post<TResponse>(req: Request) {
+ return await this.request<TResponse>("POST", req);
+ }
+}