Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(fetch-cache): fix additional typo, add type & data validation #64799

Merged
merged 8 commits into from
Apr 22, 2024
29 changes: 25 additions & 4 deletions packages/next/src/server/lib/incremental-cache/fetch-cache.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import type { CacheHandler, CacheHandlerContext, CacheHandlerValue } from './'
import type {
CachedFetchValue,
IncrementalCacheValue,
} from '../../response-cache'

import LRUCache from 'next/dist/compiled/lru-cache'

import { z } from 'next/dist/compiled/zod'
import type zod from 'next/dist/compiled/zod'

import {
CACHE_ONE_YEAR,
NEXT_CACHE_SOFT_TAGS_HEADER,
Expand All @@ -23,6 +31,18 @@ const CACHE_REVALIDATE_HEADER = 'x-vercel-revalidate' as const
const CACHE_FETCH_URL_HEADER = 'x-vercel-cache-item-name' as const
const CACHE_CONTROL_VALUE_HEADER = 'x-vercel-cache-control' as const

const zCachedFetchValue: zod.ZodType<CachedFetchValue> = z.object({
samcx marked this conversation as resolved.
Show resolved Hide resolved
kind: z.literal('FETCH'),
data: z.object({
headers: z.record(z.string()),
body: z.string(),
url: z.string(),
status: z.number().optional(),
}),
tags: z.array(z.string()).optional(),
revalidate: z.number(),
})

export default class FetchCache implements CacheHandler {
private headers: Record<string, string>
private cacheEndpoint?: string
Expand Down Expand Up @@ -233,19 +253,20 @@ export default class FetchCache implements CacheHandler {
throw new Error(`invalid response from cache ${res.status}`)
}

const cached = await res.json()
const cached: IncrementalCacheValue = await res.json()
const cachedParsed = zCachedFetchValue.safeParse(cached)

if (!cached || cached.kind !== 'FETCH') {
if (!cached || !cachedParsed.success) {
samcx marked this conversation as resolved.
Show resolved Hide resolved
this.debug && console.log({ cached })
throw new Error(`invalid cache value`)
throw new Error('invalid cache value')
}

// if new tags were specified, merge those tags to the existing tags
if (cached.kind === 'FETCH') {
cached.tags ??= []
for (const tag of tags ?? []) {
if (!cached.tags.includes(tag)) {
cached.tag.push(tag)
cached.tags.push(tag)
samcx marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
Expand Down
Loading