1- import { AppRouter , initClient , type ApiFetcherArgs } from "@ts-rest/core" ;
1+ import {
2+ AppRouter ,
3+ initClient ,
4+ tsRestFetchApi ,
5+ type ApiFetcherArgs ,
6+ } from "@ts-rest/core" ;
27import { getIdToken } from "firebase/auth" ;
38import { envConfig } from "../../constants/env-config" ;
49import { getAuthenticatedUser , isAuthenticated } from "../../firebase" ;
@@ -16,44 +21,29 @@ function buildApi(timeout: number): (args: ApiFetcherArgs) => Promise<{
1621} > {
1722 return async ( request : ApiFetcherArgs ) => {
1823 try {
19- const headers : HeadersInit = {
20- ...request . headers ,
21- "X-Client-Version" : envConfig . clientVersion ,
22- } ;
23-
2424 if ( isAuthenticated ( ) ) {
2525 const token = await getIdToken ( getAuthenticatedUser ( ) ) ;
26- headers [ "Authorization" ] = `Bearer ${ token } ` ;
26+ request . headers [ "Authorization" ] = `Bearer ${ token } ` ;
2727 }
2828
29- const fetchOptions : RequestInit = {
30- method : request . method ,
31- headers,
32- body : request . body ,
33- } ;
34-
3529 const usePolyfill = AbortSignal ?. timeout === undefined ;
3630
37- const response = await fetch ( request . path , {
38- ...fetchOptions ,
31+ request . fetchOptions = {
32+ ...( request . fetchOptions || { } ) ,
3933 signal : usePolyfill
4034 ? timeoutSignal ( timeout )
4135 : AbortSignal . timeout ( timeout ) ,
42- } ) ;
36+ } ;
37+ const response = await tsRestFetchApi ( request ) ;
4338
44- const body = ( await response . json ( ) ) as object ;
4539 if ( response . status >= 400 ) {
4640 console . error ( `${ request . method } ${ request . path } failed` , {
4741 status : response . status ,
48- ...body ,
42+ ...( response . body as object ) ,
4943 } ) ;
5044 }
5145
52- return {
53- status : response . status ,
54- body,
55- headers : response . headers ?? new Headers ( ) ,
56- } ;
46+ return response ;
5747 } catch ( e : Error | unknown ) {
5848 let message = "Unknown error" ;
5949
@@ -86,6 +76,7 @@ export function buildClient<T extends AppRouter>(
8676 api : buildApi ( timeout ) ,
8777 baseHeaders : {
8878 Accept : "application/json" ,
79+ "X-Client-Version" : envConfig . clientVersion ,
8980 } ,
9081 } ) ;
9182}
0 commit comments