新しいワーカー機能(5ドル追加)はこれを容易にすることができます:
重要なポイント:
Cloudflareは通常、通常の静的ファイルをほとんど期限切れにならないものとして扱います(または、おそらく1か月でした-私は正確に忘れています)。
だから最初は思うかもしれません"I just want to add .json to the list of static extensions"
。これは、JSONで必要とされない可能性があります(実際にめったに変更されない限り)、またはファイル名でバージョン管理されます。ファイルを更新するとその時間内に更新されますが、サーバーがすべてのエンドユーザーからの個別の要求に襲われないように、おそらく60秒または5分のようなものが必要です。
.json
すべての拡張ファイルをインターセプトするためにワーカーを使用してこれを行った方法は次のとおりです。
// Note: there could be tiny cut and paste bugs in here - please fix if you find!
addEventListener('fetch', event => {
event.respondWith(handleRequest(event));
});
async function handleRequest(event)
{
let request = event.request;
let ttl = undefined;
let cache = caches.default;
let url = new URL(event.request.url);
let shouldCache = false;
// cache JSON files with custom max age
if (url.pathname.endsWith('.json'))
{
shouldCache = true;
ttl = 60;
}
// look in cache for existing item
let response = await cache.match(request);
if (!response)
{
// fetch URL
response = await fetch(request);
// if the resource should be cached then put it in cache using the cache key
if (shouldCache)
{
// clone response to be able to edit headers
response = new Response(response.body, response);
if (ttl)
{
// https://developers.cloudflare.com/workers/recipes/vcl-conversion/controlling-the-cache/
response.headers.append('Cache-Control', 'max-age=' + ttl);
}
// put into cache (need to clone again)
event.waitUntil(cache.put(request, response.clone()));
}
return response;
}
else {
return response;
}
}
拡張機能の代わりにmime-typeを使用してこれを行うこともできますが、API応答を過剰にキャッシュしてしまう可能性があるため、非常に危険です。
また、ファイル名でバージョン管理している場合-例:products-1.json
/products-2.json
その後、有効期限のヘッダーを設定する必要はありませんmax-age
。