Skip to content

Commit

Permalink
Allow opting out of caching (kotx#16)
Browse files Browse the repository at this point in the history
Closes kotx#15
  • Loading branch information
davej authored Sep 7, 2022
1 parent bbfbe08 commit 40292fe
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ You can also do this from the [Cloudflare dashboard](https://dash.cloudflare.com
Edit `wrangler.toml` to have the correct `bucket_name` and optionally, `preview_bucket_name` (you can set it to `bucket_name`) if you're going to run this locally.
You can do this from a fork, if using the [GitHub Actions method](#method-2-github-actions).

You may edit `CACHE_CONTROL` to the default [`cache-control` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control) or remove it entirely to fall back to nothing.
You may edit `CACHE_CONTROL` to the default [`cache-control` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control) or remove it entirely to fall back to nothing. If you set `CACHE_CONTROL` to `"no-store"` then Cloudflare caching will not be used.

### Deploying

Expand Down
13 changes: 9 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,13 @@ export default {
return new Response("OK");
}

let response: Response | undefined;

const isCachingEnabled = env.CACHE_CONTROL !== "no-store"
const cache = caches.default;
let response = await cache.match(request);
if (isCachingEnabled) {
response = await cache.match(request);
}

// Since we produce this result from the request, we don't need to strictly use an R2Range
let range: ParsedRange | undefined;
Expand Down Expand Up @@ -138,8 +143,8 @@ export default {
"access-control-allow-origin": env.ALLOWED_ORIGINS || "",

"etag": file.httpEtag,
"cache-control": file.httpMetadata.cacheControl ?? (env.CACHE_CONTROL || ""),
"expires": file.httpMetadata.cacheExpiry?.toUTCString() ?? "",
"cache-control": file.httpMetadata?.cacheControl ?? (env.CACHE_CONTROL || ""),
"expires": file.httpMetadata?.cacheExpiry?.toUTCString() ?? "",
"last-modified": file.uploaded.toUTCString(),

"content-encoding": file.httpMetadata?.contentEncoding ?? "",
Expand All @@ -151,7 +156,7 @@ export default {
}
});

if (request.method === "GET" && !range)
if (request.method === "GET" && !range && isCachingEnabled)
ctx.waitUntil(cache.put(request, response.clone()));
}

Expand Down

0 comments on commit 40292fe

Please sign in to comment.