query, variables, operationName) as part of the cache key, and uses the Cache API to write the response content to the edge function's independent cache. When the cache is hit, the cached content is returned directly. When the cache is missed, the Fetch API is used to initiate a subrequest to obtain data and write it to the cache. Requests that modify data, such as mutation and subscription, are not cached. You can determine whether the cache is hit by checking the x-edgefunctions-cache response header.eo.cacheKey. If eo.cacheKey is not included, the write operation is rejected and a forbidden cdn cache error is thrown. For details, see Cache API.event.request. This example hashes the URL, operationName, variables, and query and writes them together into eo.cacheKey.mutation and subscription modify data and cannot be cached. This example makes a simplified judgment based on the operation type, and in production environments, it is recommended to use a GraphQL parsing library or a query allowlist. Requests that carry identity information such as Authorization and Cookie skip the cache by default to prevent different users from hitting the same cached content.// Cache duration (seconds), adjustable based on business needsconst CACHE_TTL = 10;// Requests carrying user identity information skip the cache by default to prevent different users from hitting the same cached contentconst SKIP_PRIVATE_REQUESTS = true;function uint8ArrayToHex(arr) {return Array.prototype.map.call(arr, (x) => (('0' + x.toString(16)).slice(-2))).join('');}// sha256 signature digestasync function sha256(message) {const msgBuffer = new TextEncoder().encode(message);const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);return uint8ArrayToHex(new Uint8Array(hashBuffer));}// Parse GraphQL requests: return null for non-POST requests, requests carrying identity information, and non-query operations (mutation/subscription)async function parseGraphQLRequest(request) {if (request.method.toUpperCase() !== 'POST') {return null;}if (SKIP_PRIVATE_REQUESTS && (request.headers.has('Authorization') || request.headers.has('Cookie'))) {return null;}let payload;try {// Read the body to construct the cache key. The subsequent fetch uses the original request whose body has not been consumed.payload = await request.clone().json();} catch (e) {return null;}if (!payload || typeof payload.query !== 'string') {return null;}// Determine the operation type after removing comments and whitespace. Mutations and subscriptions are not cached.// This is a simplified check. For cases where field names or strings contain keywords, use a GraphQL parsing library instead.const operation = payload.query.replace(/#[^\\n]*/g, ' ').trim();if (/^(mutation|subscription)\\b/i.test(operation)) {return null;}return payload;}async function fetchGraphQL(event, request, cacheKey) {const cache = caches.default;// Cache miss. Pull data from the origin.const response = await fetch(request);if (response.ok) {// Set the cache duration to ensure that origin-pull responses can be written to the cache.response.headers.set('Cache-Control', `s-maxage=${CACHE_TTL}`);event.waitUntil(cache.put(cacheKey, response.clone()));}// Cache miss. Set a response header to indicate this.response.headers.append('x-edgefunctions-cache', 'miss');return response;}async function handleRequest(event) {const request = event.request;const cache = caches.default;const payload = await parseGraphQLRequest(request);// Non-query requests go directly to the origin without caching.if (!payload) {return fetch(request);}// The cache key must uniquely identify a query: URL + operationName + variables + queryconst normalized = `${request.url}#${payload.operationName || ''}#${JSON.stringify(payload.variables || {})}#${payload.query}`;const hash = await sha256(normalized);// Use the query digest to construct the cache key, and specify reading from and writing to the independent edge function cache through eo.cacheKey.// Read, write, and delete operations must use the same Request object.const cacheKey = new Request(request.url, {eo: { cacheKey: hash },});try {// Obtain the associated cached Response.const response = await cache.match(cacheKey);if (!response) {return fetchGraphQL(event, request, cacheKey);}// Cache hit. Set a response header to indicate this.response.headers.append('x-edgefunctions-cache', 'hit');return response;} catch (error) {// For exceptions such as cache expiration (504): delete the old cache, pull from the origin again, and write the new response to the cache.try {await cache.delete(cacheKey);} catch (e) {}return fetchGraphQL(event, request, cacheKey);}}addEventListener('fetch', (event) => {event.respondWith(handleRequest(event));});


Apakah halaman ini membantu?
Anda juga dapat Menghubungi Penjualan atau Mengirimkan Tiket untuk meminta bantuan.
masukan