mirror of
https://github.com/monkeytypegame/monkeytype.git
synced 2025-10-17 02:56:16 +08:00
refactor: use tsRestFetchApi in ts-rest-adapter (@fehmer) (#6259)
This commit is contained in:
parent
365e9bb305
commit
4102e4cc24
1 changed files with 14 additions and 23 deletions
|
@ -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,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue