refactor: use tsRestFetchApi in ts-rest-adapter (@fehmer) (#6259)

This commit is contained in:
Christian Fehmer 2025-02-12 13:23:04 +01:00 committed by GitHub
parent 365e9bb305
commit 4102e4cc24
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -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<T extends AppRouter>(
api: buildApi(timeout),
baseHeaders: {
Accept: "application/json",
"X-Client-Version": envConfig.clientVersion,
},
});
}