@@ -747,16 +747,15 @@ function wrapOnCallHandler<Req = any, Res = any>(
747
747
const abortController = new AbortController ( ) ;
748
748
let heartbeatInterval : NodeJS . Timeout | null = null ;
749
749
750
- const cleanup = ( ) => {
750
+ const clearHeartbeatInterval = ( ) => {
751
751
if ( heartbeatInterval ) {
752
752
clearInterval ( heartbeatInterval ) ;
753
753
heartbeatInterval = null ;
754
754
}
755
- req . removeAllListeners ( 'close' ) ;
756
- } ;
755
+ }
757
756
758
757
req . on ( 'close' , ( ) => {
759
- cleanup ( )
758
+ clearHeartbeatInterval ( ) ;
760
759
abortController . abort ( ) ;
761
760
} ) ;
762
761
@@ -859,24 +858,24 @@ function wrapOnCallHandler<Req = any, Res = any>(
859
858
// For some reason the type system isn't picking up that the handler
860
859
// is a one argument function.
861
860
result = await ( handler as any ) ( arg , responseProxy ) ;
862
-
863
- if ( heartbeatInterval ) {
864
- clearInterval ( heartbeatInterval ) ;
865
- heartbeatInterval = null ;
866
- }
861
+ clearHeartbeatInterval ( ) ;
867
862
}
868
863
869
- // Encode the result as JSON to preserve types like Dates.
870
- result = encode ( result ) ;
864
+ if ( ! abortController . signal . aborted ) {
865
+ // Encode the result as JSON to preserve types like Dates.
866
+ result = encode ( result ) ;
871
867
872
- // If there was some result, encode it in the body.
873
- const responseBody : HttpResponseBody = { result } ;
868
+ // If there was some result, encode it in the body.
869
+ const responseBody : HttpResponseBody = { result } ;
874
870
875
- if ( acceptsStreaming ) {
876
- res . write ( encodeSSE ( responseBody ) ) ;
877
- res . end ( ) ;
871
+ if ( acceptsStreaming ) {
872
+ res . write ( encodeSSE ( responseBody ) ) ;
873
+ res . end ( ) ;
874
+ } else {
875
+ res . status ( 200 ) . send ( responseBody ) ;
876
+ }
878
877
} else {
879
- res . status ( 200 ) . send ( responseBody ) ;
878
+ res . end ( ) ;
880
879
}
881
880
} catch ( err ) {
882
881
if ( ! abortController . signal . aborted ) {
@@ -894,9 +893,11 @@ function wrapOnCallHandler<Req = any, Res = any>(
894
893
} else {
895
894
res . status ( status ) . send ( body ) ;
896
895
}
896
+ } else {
897
+ res . end ( ) ;
897
898
}
898
899
} finally {
899
- cleanup ( ) ;
900
+ clearHeartbeatInterval ( ) ;
900
901
}
901
902
} ;
902
903
}
0 commit comments