import { AnyRouter } from '@trpc/server' ; import { TRPCClientError } from '../TRPCClientError' ; import { transformRPCResponse } from '../internals/transformRPCResponse' ; import { httpRequest } from '../internals/httpRequest' ; import { HTTPLinkOptions , TRPCLink } from './core' ; import { TRPCAbortError } from '../internals/TRPCAbortError' ; export function httpLink < TRouter extends AnyRouter > ( opts ) { const { url } = opts ; return ( runtime ) => { return ( { op , prev , onDestroy } ) => { const { path , input , type } = op ; const { promise , cancel } = httpRequest ( { runtime , type , input , url , path } ) ; let isDone = false ; const prevOnce = ( result ) => { if ( isDone ) { return ; } isDone = true ; prev ( result ) ; } ; onDestroy ( ( ) => { prevOnce ( TRPCClientError . from ( new TRPCAbortError ( ) , { isDone : true } ) ) ; cancel ( ) ; } ) ; promise . then ( ( envelope ) => { prevOnce ( transformRPCResponse ( { envelope , runtime } ) ) ; } ) . catch ( ( cause ) => { prevOnce ( TRPCClientError . from ( cause ) ) ; } ) ; } ; } ; }