From 4102e4cc24d537dd6eb0937b54e189ae299b87c0 Mon Sep 17 00:00:00 2001 From: Christian Fehmer Date: Wed, 12 Feb 2025 13:23:04 +0100 Subject: [PATCH] refactor: use tsRestFetchApi in ts-rest-adapter (@fehmer) (#6259) --- .../src/ts/ape/adapters/ts-rest-adapter.ts | 37 +++++++------------ 1 file changed, 14 insertions(+), 23 deletions(-) diff --git a/frontend/src/ts/ape/adapters/ts-rest-adapter.ts b/frontend/src/ts/ape/adapters/ts-rest-adapter.ts index bba9590d9..5ca100350 100644 --- a/frontend/src/ts/ape/adapters/ts-rest-adapter.ts +++ b/frontend/src/ts/ape/adapters/ts-rest-adapter.ts @@ -1,4 +1,9 @@ -import { AppRouter, initClient, type ApiFetcherArgs } from "@ts-rest/core"; +import { + AppRouter, + initClient, + tsRestFetchApi, + type ApiFetcherArgs, +} from "@ts-rest/core"; import { getIdToken } from "firebase/auth"; import { envConfig } from "../../constants/env-config"; import { getAuthenticatedUser, isAuthenticated } from "../../firebase"; @@ -16,44 +21,29 @@ function buildApi(timeout: number): (args: ApiFetcherArgs) => Promise<{ }> { return async (request: ApiFetcherArgs) => { try { - const headers: HeadersInit = { - ...request.headers, - "X-Client-Version": envConfig.clientVersion, - }; - if (isAuthenticated()) { const token = await getIdToken(getAuthenticatedUser()); - headers["Authorization"] = `Bearer ${token}`; + request.headers["Authorization"] = `Bearer ${token}`; } - const fetchOptions: RequestInit = { - method: request.method, - headers, - body: request.body, - }; - const usePolyfill = AbortSignal?.timeout === undefined; - const response = await fetch(request.path, { - ...fetchOptions, + request.fetchOptions = { + ...(request.fetchOptions || {}), signal: usePolyfill ? timeoutSignal(timeout) : AbortSignal.timeout(timeout), - }); + }; + const response = await tsRestFetchApi(request); - const body = (await response.json()) as object; if (response.status >= 400) { console.error(`${request.method} ${request.path} failed`, { status: response.status, - ...body, + ...(response.body as object), }); } - return { - status: response.status, - body, - headers: response.headers ?? new Headers(), - }; + return response; } catch (e: Error | unknown) { let message = "Unknown error"; @@ -86,6 +76,7 @@ export function buildClient( api: buildApi(timeout), baseHeaders: { Accept: "application/json", + "X-Client-Version": envConfig.clientVersion, }, }); }