Skip to content

Commit d6a7ca0

Browse files
samcxhuozhi
authored andcommitted
fix(fetch-cache): fix additional typo, add type & data validation (#64799)
This PR fixes the fetch cache, which currently is not using the fetch cache when it exists (the tags were not getting set properly), and tags have not updated. (Before) https://github.com/vercel/next.js/assets/28912696/74d8f592-0698-4ae4-be4b-30cffb1ffe11 (After) https://github.com/vercel/next.js/assets/28912696/af12b13a-46c6-41c3-9ac3-20e1ec44a865 - #64786 - #63547 Closes NEXT-3173
1 parent 4a6b511 commit d6a7ca0

File tree

1 file changed

+29
-6
lines changed

1 file changed

+29
-6
lines changed

packages/next/src/server/lib/incremental-cache/fetch-cache.ts

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
11
import type { CacheHandler, CacheHandlerContext, CacheHandlerValue } from './'
2+
import type {
3+
CachedFetchValue,
4+
IncrementalCacheValue,
5+
} from '../../response-cache'
26

37
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+
412
import {
513
CACHE_ONE_YEAR,
614
NEXT_CACHE_SOFT_TAGS_HEADER,
@@ -23,6 +31,18 @@ const CACHE_REVALIDATE_HEADER = 'x-vercel-revalidate' as const
2331
const CACHE_FETCH_URL_HEADER = 'x-vercel-cache-item-name' as const
2432
const CACHE_CONTROL_VALUE_HEADER = 'x-vercel-cache-control' as const
2533

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+
2646
export default class FetchCache implements CacheHandler {
2747
private headers: Record<string, string>
2848
private cacheEndpoint?: string
@@ -233,19 +253,22 @@ export default class FetchCache implements CacheHandler {
233253
throw new Error(`invalid response from cache ${res.status}`)
234254
}
235255

236-
const cached = await res.json()
256+
const json: IncrementalCacheValue = await res.json()
257+
const parsed = zCachedFetchValue.safeParse(json)
237258

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')
241262
}
242263

264+
const { data: cached } = parsed
265+
243266
// if new tags were specified, merge those tags to the existing tags
244267
if (cached.kind === 'FETCH') {
245268
cached.tags ??= []
246269
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)
249272
}
250273
}
251274
}

0 commit comments

Comments
 (0)