Cache API 사용하기
Cache API를 사용해 R2 객체를 Cloudflare의 캐시에 저장해 볼 거예요. 이렇게 하면 반복되는 요청을 더 빠르게 처리할 수 있어요.
출처: 문서
본문
Cache API를 사용해 R2 객체를 Cloudflare의 캐시에 저장해요.
참고
Cache API를 사용하려면 Worker에 커스텀 도메인 연결 또는 라우트 설정이 필요해요. Cloudflare Workers 대시보드 편집기, Playground 프리뷰, 그리고 모든
*.workers.dev배포에서 수행한 Cache API 작업은 아무런 영향을 미치지 않아요.
export default {
async fetch(request, env, context) {
try {
const url = new URL(request.url);
// Construct the cache key from the cache URL
const cacheKey = new Request(url.toString(), request);
const cache = caches.default;
// Check whether the value is already available in the cache
// if not, you will need to fetch it from R2, and store it in the cache
// for future access
let response = await cache.match(cacheKey);
if (response) {
console.log(`Cache hit for: ${request.url}.`);
return response;
}
console.log(
`Response for request url: ${request.url} not present in cache. Fetching and caching request.`
);
// If not in cache, get it from R2
const objectKey = url.pathname.slice(1);
const object = await env.MY_BUCKET.get(objectKey);
if (object === null) {
return new Response('Object Not Found', { status: 404 });
}
// Set the appropriate object headers
const headers = new Headers();
object.writeHttpMetadata(headers);
headers.set('etag', object.httpEtag);
// Cache API respects Cache-Control headers. Setting s-max-age to 10
// will limit the response to be in cache for 10 seconds max
// Any changes made to the response here will be reflected in the cached value
headers.append('Cache-Control', 's-maxage=10');
response = new Response(object.body, {
headers,
});
// Store the fetched response as cacheKey
// Use waitUntil so you can return the response without blocking on
// writing to cache
context.waitUntil(cache.put(cacheKey, response.clone()));
return response;
} catch (e) {
return new Response('Error thrown ' + e.message);
}
},
};