@@ -22,19 +22,46 @@ const ResponseCache = require('next/dist/server/response-cache/index.js').defaul
22
22
const originalGet = ResponseCache . prototype . get
23
23
ResponseCache . prototype . get = function get ( ...getArgs : unknown [ ] ) {
24
24
if ( ! this . didAddBackgroundWorkTracking ) {
25
- const originalBatcherBatch = this . batcher . batch
26
- this . batcher . batch = async ( key : string , fn : ( ...args : unknown [ ] ) => unknown ) => {
27
- const trackedFn = async ( ...workFnArgs : unknown [ ] ) => {
28
- const workPromise = fn ( ...workFnArgs )
25
+ if ( typeof this . batcher !== 'undefined' ) {
26
+ const originalBatcherBatch = this . batcher . batch
27
+ this . batcher . batch = async ( key : string , fn : ( ...args : unknown [ ] ) => unknown ) => {
28
+ const trackedFn = async ( ...workFnArgs : unknown [ ] ) => {
29
+ const workPromise = fn ( ...workFnArgs )
30
+ const requestContext = getRequestContext ( )
31
+ if ( requestContext && workPromise instanceof Promise ) {
32
+ requestContext . trackBackgroundWork ( workPromise )
33
+ }
34
+ return await workPromise
35
+ }
36
+
37
+ return originalBatcherBatch . call ( this . batcher , key , trackedFn )
38
+ }
39
+ } else if ( typeof this . pendingResponses !== 'undefined' ) {
40
+ const backgroundWork = new Map < string , ( ) => void > ( )
41
+
42
+ const originalPendingResponsesSet = this . pendingResponses . set
43
+ this . pendingResponses . set = async ( key : string , value : unknown ) => {
29
44
const requestContext = getRequestContext ( )
30
- if ( requestContext && workPromise instanceof Promise ) {
45
+ if ( requestContext && ! this . pendingResponses . has ( key ) ) {
46
+ const workPromise = new Promise < void > ( ( _resolve ) => {
47
+ backgroundWork . set ( key , _resolve )
48
+ } )
49
+
31
50
requestContext . trackBackgroundWork ( workPromise )
32
51
}
33
- return await workPromise
52
+ return originalPendingResponsesSet . call ( this . pendingResponses , key , value )
34
53
}
35
54
36
- return originalBatcherBatch . call ( this . batcher , key , trackedFn )
55
+ const originalPendingResponsesDelete = this . pendingResponses . delete
56
+ this . pendingResponses . delete = async ( key : string ) => {
57
+ const _resolve = backgroundWork . get ( key )
58
+ if ( _resolve ) {
59
+ _resolve ( )
60
+ }
61
+ return originalPendingResponsesDelete . call ( this . pendingResponses , key )
62
+ }
37
63
}
64
+
38
65
this . didAddBackgroundWorkTracking = true
39
66
}
40
67
return originalGet . apply ( this , getArgs )
0 commit comments