1
1
import type { CacheHandler , CacheHandlerContext , CacheHandlerValue } from './'
2
+ import type {
3
+ CachedFetchValue ,
4
+ IncrementalCacheValue ,
5
+ } from '../../response-cache'
2
6
3
7
import LRUCache from 'next/dist/compiled/lru-cache'
8
+
9
+ import { z } from 'next/dist/compiled/zod'
10
+ import type zod from 'next/dist/compiled/zod'
11
+
4
12
import {
5
13
CACHE_ONE_YEAR ,
6
14
NEXT_CACHE_SOFT_TAGS_HEADER ,
@@ -23,6 +31,18 @@ const CACHE_REVALIDATE_HEADER = 'x-vercel-revalidate' as const
23
31
const CACHE_FETCH_URL_HEADER = 'x-vercel-cache-item-name' as const
24
32
const CACHE_CONTROL_VALUE_HEADER = 'x-vercel-cache-control' as const
25
33
34
+ const zCachedFetchValue : zod . ZodType < CachedFetchValue > = z . object ( {
35
+ kind : z . literal ( 'FETCH' ) ,
36
+ data : z . object ( {
37
+ headers : z . record ( z . string ( ) ) ,
38
+ body : z . string ( ) ,
39
+ url : z . string ( ) ,
40
+ status : z . number ( ) . optional ( ) ,
41
+ } ) ,
42
+ tags : z . array ( z . string ( ) ) . optional ( ) ,
43
+ revalidate : z . number ( ) ,
44
+ } )
45
+
26
46
export default class FetchCache implements CacheHandler {
27
47
private headers : Record < string , string >
28
48
private cacheEndpoint ?: string
@@ -233,19 +253,22 @@ export default class FetchCache implements CacheHandler {
233
253
throw new Error ( `invalid response from cache ${ res . status } ` )
234
254
}
235
255
236
- const cached = await res . json ( )
256
+ const json : IncrementalCacheValue = await res . json ( )
257
+ const parsed = zCachedFetchValue . safeParse ( json )
237
258
238
- if ( ! cached || cached . kind !== 'FETCH' ) {
239
- this . debug && console . log ( { cached } )
240
- throw new Error ( ` invalid cache value` )
259
+ if ( ! parsed . success ) {
260
+ this . debug && console . log ( { json } )
261
+ throw new Error ( ' invalid cache value' )
241
262
}
242
263
264
+ const { data : cached } = parsed
265
+
243
266
// if new tags were specified, merge those tags to the existing tags
244
267
if ( cached . kind === 'FETCH' ) {
245
268
cached . tags ??= [ ]
246
269
for ( const tag of tags ?? [ ] ) {
247
- if ( ! cached . tags . include ( tag ) ) {
248
- cached . tag . push ( tag )
270
+ if ( ! cached . tags . includes ( tag ) ) {
271
+ cached . tags . push ( tag )
249
272
}
250
273
}
251
274
}
0 commit comments