Skip to content

Commit

Permalink
Allow caching directory listings (kotx#22)
Browse files Browse the repository at this point in the history
Adds a simple `DIRECTORY_CACHE_CONTROL` option to control the
otherwise hardcoded Cache-Control header on directory listing responses.
Also place the directory listing into Cloudflare cache
if configured to do so.

The new option defaults to `no-store` and will be treated as `no-store`
if not present. This is backwards compatible with previous versions.
  • Loading branch information
Erisa authored Oct 10, 2022
1 parent 2745130 commit 9b7a4a9
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ interface Env {
NOTFOUND_FILE?: string
DIRECTORY_LISTING?: boolean
HIDE_HIDDEN_FILES?: boolean
DIRECTORY_CACHE_CONTROL?: string
}

type ParsedRange = { offset: number, length: number } | { suffix: number };
Expand Down Expand Up @@ -121,7 +122,7 @@ ${htmlList.join("\n")}
"access-control-allow-origin": env.ALLOWED_ORIGINS || "",
"last-modified": lastModified === null ? "" : lastModified.toUTCString(),
"content-type": "text/html",
"cache-control": "no-store"
"cache-control": env.DIRECTORY_CACHE_CONTROL || "no-store"
}
});
}
Expand Down Expand Up @@ -163,7 +164,12 @@ export default {
// return the dir listing
let listResponse = await makeListingResponse(path, env, request);

if (listResponse !== null) return listResponse;
if (listResponse !== null) {
if (listResponse.headers.get("cache-control") !== "no-store") {
ctx.waitUntil(cache.put(request, listResponse.clone()));
}
return listResponse;
}
}
}

Expand Down Expand Up @@ -254,7 +260,12 @@ export default {
// return the dir listing
let listResponse = await makeListingResponse(path, env, request);

if (listResponse !== null) return listResponse;
if (listResponse !== null) {
if (listResponse.headers.get("cache-control") !== "no-store") {
ctx.waitUntil(cache.put(request, listResponse.clone()));
}
return listResponse;
}
}

if (env.NOTFOUND_FILE && env.NOTFOUND_FILE != "") {
Expand Down
3 changes: 3 additions & 0 deletions wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ DIRECTORY_LISTING = false
# Enable to hide files or directories beginning with . from directory listings.
HIDE_HIDDEN_FILES = false

# Set a cache header here, e.g. "max-age=86400", if you want to cache directory listings.
DIRECTORY_CACHE_CONTROL = "no-store"

[[r2_buckets]]
binding = "R2_BUCKET"
bucket_name = "kot" # Set this to your R2 bucket name. Required
Expand Down

0 comments on commit 9b7a4a9

Please sign in to comment.