@@ -747,26 +747,31 @@ function wrapOnCallHandler<Req = any, Res = any>(
747
747
const abortController = new AbortController ( ) ;
748
748
let heartbeatInterval : NodeJS . Timeout | null = null ;
749
749
750
+ const heartbeatSeconds =
751
+ options . heartbeatSeconds === undefined
752
+ ? DEFAULT_HEARTBEAT_SECONDS
753
+ : options . heartbeatSeconds ;
754
+
750
755
const clearScheduledHeartbeat = ( ) => {
751
756
if ( heartbeatInterval ) {
752
757
clearTimeout ( heartbeatInterval ) ;
753
758
heartbeatInterval = null ;
754
759
}
755
760
} ;
756
761
757
- const scheduleHeartbeat = ( heartbeatSeconds : number ) => {
758
- clearScheduledHeartbeat ( ) ; // Clear any existing timeout
762
+ const scheduleHeartbeat = ( ) => {
763
+ clearScheduledHeartbeat ( ) ;
759
764
if ( ! abortController . signal . aborted ) {
760
765
heartbeatInterval = setTimeout ( ( ) => {
761
766
if ( ! abortController . signal . aborted ) {
762
767
res . write ( ": ping\n" ) ;
763
- scheduleHeartbeat ( heartbeatSeconds ) ;
768
+ scheduleHeartbeat ( ) ;
764
769
}
765
770
} , heartbeatSeconds * 1000 ) ;
766
771
}
767
772
} ;
768
773
769
- req . on ( "close" , ( ) => {
774
+ res . on ( "close" , ( ) => {
770
775
clearScheduledHeartbeat ( ) ;
771
776
abortController . abort ( ) ;
772
777
} ) ;
@@ -841,27 +846,24 @@ function wrapOnCallHandler<Req = any, Res = any>(
841
846
data,
842
847
} ;
843
848
844
- const heartbeatSeconds =
845
- options . heartbeatSeconds === undefined
846
- ? DEFAULT_HEARTBEAT_SECONDS
847
- : options . heartbeatSeconds ;
848
-
849
849
const responseProxy : CallableProxyResponse = {
850
850
write ( chunk ) : boolean {
851
851
// if client doesn't accept sse-protocol, response.write() is no-op.
852
852
if ( ! acceptsStreaming ) {
853
853
return false ;
854
854
}
855
+
855
856
// if connection is already closed, response.write() is no-op.
856
857
if ( abortController . signal . aborted ) {
857
858
return false ;
858
859
}
860
+
859
861
const formattedData = encodeSSE ( { message : chunk } ) ;
860
862
const wrote = res . write ( formattedData ) ;
861
- //
863
+
862
864
// Reset heartbeat timer after successful write
863
865
if ( wrote && heartbeatInterval !== null && heartbeatSeconds > 0 ) {
864
- scheduleHeartbeat ( heartbeatSeconds ) ;
866
+ scheduleHeartbeat ( ) ;
865
867
}
866
868
return wrote ;
867
869
} ,
@@ -873,7 +875,7 @@ function wrapOnCallHandler<Req = any, Res = any>(
873
875
res . status ( 200 ) ;
874
876
875
877
if ( heartbeatSeconds !== null && heartbeatSeconds > 0 ) {
876
- scheduleHeartbeat ( heartbeatSeconds ) ;
878
+ scheduleHeartbeat ( ) ;
877
879
}
878
880
}
879
881
// For some reason the type system isn't picking up that the handler
0 commit comments