-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathrevalidate.ts
37 lines (30 loc) · 1.23 KB
/
revalidate.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import type { ServerResponse } from 'node:http'
import { isPromise } from 'node:util/types'
import type { NextApiResponse } from 'next'
import type { RequestContext } from './handlers/request-context.cjs'
type ResRevalidateMethod = NextApiResponse['revalidate']
function isRevalidateMethod(
key: string,
nextResponseField: unknown,
): nextResponseField is ResRevalidateMethod {
return key === 'revalidate' && typeof nextResponseField === 'function'
}
// Needing to proxy the response object to intercept the revalidate call for on-demand revalidation on page routes
export const nextResponseProxy = (response: ServerResponse, requestContext: RequestContext) => {
return new Proxy(response, {
get(target: ServerResponse, key: string) {
const originalValue = Reflect.get(target, key)
if (isRevalidateMethod(key, originalValue)) {
return function newRevalidate(...args: Parameters<ResRevalidateMethod>) {
requestContext.didPagesRouterOnDemandRevalidate = true
const result = originalValue.apply(target, args)
if (result && isPromise(result)) {
requestContext.trackBackgroundWork(result)
}
return result
}
}
return originalValue
},
})
}