From f69e40ae9e28b38a882105ff9065545ccbe8255e Mon Sep 17 00:00:00 2001 From: Fabian Stamm Date: Sun, 2 Aug 2020 16:42:05 +0200 Subject: [PATCH] Fixing cache control --- registry/src/http/api.ts | 17 +++++++++++++---- registry/src/http/raw.ts | 17 +++++++++++++++++ registry/src/http/views.ts | 13 +++++++------ 3 files changed, 37 insertions(+), 10 deletions(-) diff --git a/registry/src/http/api.ts b/registry/src/http/api.ts index 2a49642..4ec9b55 100644 --- a/registry/src/http/api.ts +++ b/registry/src/http/api.ts @@ -8,12 +8,21 @@ import db, { IPackage } from "../db.ts"; import { v4 } from "https://deno.land/std/uuid/mod.ts"; export default function api(g: ABC.Group) { - g.get("/", (ctx) => { - return { version: "1" }; - }); + const cacheControl = (next) => (ctx) => { + ctx.response.headers.set("cache-control", "private"); + next(ctx); + }; + + g.get( + "/", + (ctx) => { + return { version: "1" }; + }, + cacheControl + ); // g.post("/getapikey", getApiKey, basicauth("api")); - g.post("/package/:name", uploadPackage, basicauth("api")); + g.post("/package/:name", uploadPackage, cacheControl, basicauth("api")); } // async function getApiKey(ctx: ABC.Context) { diff --git a/registry/src/http/raw.ts b/registry/src/http/raw.ts index 0bb13f3..e0acaf0 100644 --- a/registry/src/http/raw.ts +++ b/registry/src/http/raw.ts @@ -1,6 +1,9 @@ import { ABC } from "../deps.ts"; import { extractPackagePath, getFile } from "../utils.ts"; +const MAX_FIXED_CACHE_AGE = 60 * 60 * 24 * 365; +const MAX_FLOATING_CACHE_AGE = 60 * 30; + export default function raw(g: ABC.Group) { g.get("/:package/*path", async (ctx) => { console.log(ctx.params, ctx.path); @@ -18,7 +21,21 @@ export default function raw(g: ABC.Group) { packageVersion, ctx.params.path ); + + if (packageVersion && result) { + ctx.response.headers.set( + "cache-control", + "public, max-age=" + MAX_FIXED_CACHE_AGE + ); + } else { + ctx.response.headers.set( + "cache-control", + "no-cache, max-age=" + MAX_FLOATING_CACHE_AGE + ); + } + if (!result) return E404(); + ctx.response.headers.set("e-tag", result.etag); return result.data; }); diff --git a/registry/src/http/views.ts b/registry/src/http/views.ts index 0109f64..b7713e9 100644 --- a/registry/src/http/views.ts +++ b/registry/src/http/views.ts @@ -23,6 +23,11 @@ export default function views(g: ABC.Application) { packages = await db.package.find({}); } + ctx.render("index", { + packages, + search, + }); + const etag = "W/" + Hash.createHash("sha3-256") @@ -36,12 +41,8 @@ export default function views(g: ABC.Application) { ) .toString("base64"); - ctx.response.headers.set("e-tag", etag); - - return ctx.render("index", { - packages, - search, - }); + ctx.response.headers.set("cache-control", CACHE_CONTROL); + ctx.response.headers.set("E-Tag", etag); }); g.get("/package/:package", async (ctx) => { let [packageName, packageVersion] = extractPackagePath(