|
| 1 | +/** |
| 2 | + * Based on https://github.com/facebook/react/blob/d4e78c42a94be027b4dc7ed2659a5fddfbf9bd4e/packages/react/src/ReactFetch.js |
| 3 | + */ |
| 4 | +import * as React from 'react' |
| 5 | +import { cloneResponse } from './clone-response' |
| 6 | + |
| 7 | +const simpleCacheKey = '["GET",[],null,"follow",null,null,null,null]' // generateCacheKey(new Request('https://blank')); |
| 8 | + |
| 9 | +function generateCacheKey(request: Request): string { |
| 10 | + // We pick the fields that goes into the key used to dedupe requests. |
| 11 | + // We don't include the `cache` field, because we end up using whatever |
| 12 | + // caching resulted from the first request. |
| 13 | + // Notably we currently don't consider non-standard (or future) options. |
| 14 | + // This might not be safe. TODO: warn for non-standard extensions differing. |
| 15 | + // IF YOU CHANGE THIS UPDATE THE simpleCacheKey ABOVE. |
| 16 | + return JSON.stringify([ |
| 17 | + request.method, |
| 18 | + Array.from(request.headers.entries()), |
| 19 | + request.mode, |
| 20 | + request.redirect, |
| 21 | + request.credentials, |
| 22 | + request.referrer, |
| 23 | + request.referrerPolicy, |
| 24 | + request.integrity, |
| 25 | + ]) |
| 26 | +} |
| 27 | + |
| 28 | +type CacheEntry = [ |
| 29 | + key: string, |
| 30 | + promise: Promise<Response>, |
| 31 | + response: Response | null |
| 32 | +] |
| 33 | + |
| 34 | +export function createDedupeFetch(originalFetch: typeof fetch) { |
| 35 | + const getCacheEntries = React.cache( |
| 36 | + // eslint-disable-next-line @typescript-eslint/no-unused-vars -- url is the cache key |
| 37 | + (url: string): CacheEntry[] => [] |
| 38 | + ) |
| 39 | + |
| 40 | + return function dedupeFetch( |
| 41 | + resource: URL | RequestInfo, |
| 42 | + options?: RequestInit |
| 43 | + ): Promise<Response> { |
| 44 | + if (options && options.signal) { |
| 45 | + // If we're passed a signal, then we assume that |
| 46 | + // someone else controls the lifetime of this object and opts out of |
| 47 | + // caching. It's effectively the opt-out mechanism. |
| 48 | + // Ideally we should be able to check this on the Request but |
| 49 | + // it always gets initialized with its own signal so we don't |
| 50 | + // know if it's supposed to override - unless we also override the |
| 51 | + // Request constructor. |
| 52 | + return originalFetch(resource, options) |
| 53 | + } |
| 54 | + // Normalize the Request |
| 55 | + let url: string |
| 56 | + let cacheKey: string |
| 57 | + if (typeof resource === 'string' && !options) { |
| 58 | + // Fast path. |
| 59 | + cacheKey = simpleCacheKey |
| 60 | + url = resource |
| 61 | + } else { |
| 62 | + // Normalize the request. |
| 63 | + // if resource is not a string or a URL (its an instance of Request) |
| 64 | + // then do not instantiate a new Request but instead |
| 65 | + // reuse the request as to not disturb the body in the event it's a ReadableStream. |
| 66 | + const request = |
| 67 | + typeof resource === 'string' || resource instanceof URL |
| 68 | + ? new Request(resource, options) |
| 69 | + : resource |
| 70 | + if ( |
| 71 | + (request.method !== 'GET' && request.method !== 'HEAD') || |
| 72 | + request.keepalive |
| 73 | + ) { |
| 74 | + // We currently don't dedupe requests that might have side-effects. Those |
| 75 | + // have to be explicitly cached. We assume that the request doesn't have a |
| 76 | + // body if it's GET or HEAD. |
| 77 | + // keepalive gets treated the same as if you passed a custom cache signal. |
| 78 | + return originalFetch(resource, options) |
| 79 | + } |
| 80 | + cacheKey = generateCacheKey(request) |
| 81 | + url = request.url |
| 82 | + } |
| 83 | + |
| 84 | + const cacheEntries = getCacheEntries(url) |
| 85 | + for (let i = 0, j = cacheEntries.length; i < j; i += 1) { |
| 86 | + const [key, promise] = cacheEntries[i] |
| 87 | + if (key === cacheKey) { |
| 88 | + return promise.then(() => { |
| 89 | + const response = cacheEntries[i][2] |
| 90 | + if (!response) throw new Error('No cached response') |
| 91 | + |
| 92 | + // We're cloning the response using this utility because there exists |
| 93 | + // a bug in the undici library around response cloning. See the |
| 94 | + // following pull request for more details: |
| 95 | + // https://github.com/vercel/next.js/pull/73274 |
| 96 | + const [cloned1, cloned2] = cloneResponse(response) |
| 97 | + cacheEntries[i][2] = cloned2 |
| 98 | + return cloned1 |
| 99 | + }) |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + // We pass the original arguments here in case normalizing the Request |
| 104 | + // doesn't include all the options in this environment. We also pass a |
| 105 | + // signal down to the original fetch as to bypass the underlying React fetch |
| 106 | + // cache. |
| 107 | + const controller = new AbortController() |
| 108 | + const promise = originalFetch(resource, { |
| 109 | + ...options, |
| 110 | + signal: controller.signal, |
| 111 | + }) |
| 112 | + const entry: CacheEntry = [cacheKey, promise, null] |
| 113 | + cacheEntries.push(entry) |
| 114 | + |
| 115 | + return promise.then((response) => { |
| 116 | + // We're cloning the response using this utility because there exists |
| 117 | + // a bug in the undici library around response cloning. See the |
| 118 | + // following pull request for more details: |
| 119 | + // https://github.com/vercel/next.js/pull/73274 |
| 120 | + const [cloned1, cloned2] = cloneResponse(response) |
| 121 | + entry[2] = cloned2 |
| 122 | + return cloned1 |
| 123 | + }) |
| 124 | + } |
| 125 | +} |
0 commit comments