Created
June 14, 2020 23:48
-
-
Save ItsWendell/0c55921f81d1e9ef8f5510df4d664f65 to your computer and use it in GitHub Desktop.
Helper function for setting cache control from HTTP server responses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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