tencent cloud

DokumentasiTencent Cloud EdgeOne

Caching GraphQL Requests

Unduh
Mode fokus
Ukuran font
Terakhir diperbarui: 2026-11-03 14:58:01
Diterjemahkan & Diperiksa oleh AI
This example calculates the SHA-256 digest of the GraphQL query request body (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.
Note:
Read, write, and delete operations must use the same Request object that specifies 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.
GraphQL requests typically share a single endpoint (the same URL). Using only the URL as the cache key causes different queries to overwrite each other, so the cache key must include the query statement and variables. In addition, the cache key request supports only the GET method and cannot directly use the POST event.request. This example hashes the URL, operationName, variables, and query and writes them together into eo.cacheKey.
Only queries are cached: 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.

Sample Code

// Cache duration (seconds), adjustable based on business needs
const CACHE_TTL = 10;

// Requests carrying user identity information skip the cache by default to prevent different users from hitting the same cached content
const SKIP_PRIVATE_REQUESTS = true;

function uint8ArrayToHex(arr) {
return Array.prototype.map.call(arr, (x) => (('0' + x.toString(16)).slice(-2))).join('');
}

// sha256 signature digest
async 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 + query
const 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));
});

Sample Preview

The cache is not hit.

The cache is hit.


Related References

Bantuan dan Dukungan

Apakah halaman ini membantu?

masukan