Skip to content

Instantly share code, notes, and snippets.

@ItsWendell
Created June 14, 2020 23:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ItsWendell/0c55921f81d1e9ef8f5510df4d664f65 to your computer and use it in GitHub Desktop.
Save ItsWendell/0c55921f81d1e9ef8f5510df4d664f65 to your computer and use it in GitHub Desktop.
Helper function for setting cache control from HTTP server responses
import { ServerResponse } from "http";
interface CacheControlConfig {
sMaxAge?: number;
maxAge?: number;
staleWhileRevalidate?: boolean | number;
publicCache?: boolean;
privateCache?: boolean;
immutable?: boolean;
noCache?: boolean;
noStore?: boolean;
}
export const setCacheControl = ({
sMaxAge,
maxAge,
staleWhileRevalidate,
publicCache,
privateCache,
immutable,
noCache,
noStore,
}: CacheControlConfig) => async (res: ServerResponse) => {
if (noCache && immutable) {
throw Error("You cannot use no-cache in-conjunction with immutable.");
}
const properties: string[] = [];
if (publicCache) {
properties.push("public");
}
if (privateCache) {
properties.push("private");
}
if (noCache) {
properties.push("no-cache");
}
if (noStore) {
properties.push("no-store");
}
if (typeof sMaxAge !== "undefined") {
properties.push(`s-maxage=${sMaxAge}`);
}
if (typeof maxAge !== "undefined") {
properties.push(`max-age=${maxAge}`);
}
if (typeof staleWhileRevalidate === "number") {
properties.push(`stale-while-revalidate=${staleWhileRevalidate}`);
}
if (typeof staleWhileRevalidate === "boolean" && staleWhileRevalidate) {
properties.push(`stale-while-revalidate`);
}
const header = properties.join(", ");
res.setHeader("Cache-Control", header);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment