@@ -25,7 +25,8 @@ async function flushWithTimeout(timeout: number): Promise<void> {
25
25
* The function is async, but in environments that support a `waitUntil` mechanism, it will run synchronously.
26
26
*
27
27
* This function is aware of the following serverless platforms:
28
- * - Cloudflare: If a Cloudflare context is provided, it will use `ctx.waitUntil()` to flush events.
28
+ * - Cloudflare: If a Cloudflare context is provided, it will use `ctx.waitUntil()` to flush events (keeps the `this` context of `ctx`).
29
+ * If a `cloudflareWaitUntil` function is provided, it will use that to flush events (looses the `this` context of `ctx`).
29
30
* - Vercel: It detects the Vercel environment and uses Vercel's `waitUntil` function.
30
31
* - Other Serverless (AWS Lambda, Google Cloud, etc.): It detects the environment via environment variables
31
32
* and uses a regular `await flush()`.
@@ -34,15 +35,19 @@ async function flushWithTimeout(timeout: number): Promise<void> {
34
35
* @hidden
35
36
*/
36
37
export async function flushIfServerless (
37
- params : {
38
- timeout ?: number ;
39
- cloudflareCtx ?: MinimalCloudflareContext ;
40
- } = { } ,
38
+ params : // eslint-disable-next-line @typescript-eslint/no-explicit-any
39
+ | { timeout ?: number ; cloudflareWaitUntil ?: ( task : Promise < any > ) => void }
40
+ | { timeout ?: number ; cloudflareCtx ?: MinimalCloudflareContext } ,
41
41
) : Promise < void > {
42
- const { timeout = 2000 , cloudflareCtx } = params ;
42
+ const { timeout = 2000 } = params ;
43
43
44
- if ( cloudflareCtx && typeof cloudflareCtx . waitUntil === 'function' ) {
45
- cloudflareCtx . waitUntil ( flushWithTimeout ( timeout ) ) ;
44
+ if ( 'cloudflareWaitUntil' in params && typeof params ?. cloudflareWaitUntil === 'function' ) {
45
+ params . cloudflareWaitUntil ( flushWithTimeout ( timeout ) ) ;
46
+ return ;
47
+ }
48
+
49
+ if ( 'cloudflareCtx' in params && typeof params . cloudflareCtx ?. waitUntil === 'function' ) {
50
+ params . cloudflareCtx . waitUntil ( flushWithTimeout ( timeout ) ) ;
46
51
return ;
47
52
}
48
53
0 commit comments