Skip to content

Commit a1d4cb9

Browse files
committed
refactor: normalize cacheControl handling in response headers
1 parent d66f6b8 commit a1d4cb9

1 file changed

Lines changed: 22 additions & 26 deletions

File tree

src/middleware.js

Lines changed: 22 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -576,37 +576,33 @@ function wrapper(context) {
576576
? true
577577
: context.options.cacheImmutable;
578578

579-
const cacheControl =
580-
hasCacheImmutable && extra.immutable
581-
? { immutable: true }
582-
: context.options.cacheControl;
583-
584-
if (cacheControl) {
585-
let cacheControlValue;
586-
587-
if (typeof cacheControl === "boolean") {
588-
cacheControlValue = "public, max-age=31536000";
589-
} else if (typeof cacheControl === "number") {
590-
const maxAge = Math.floor(
591-
Math.min(Math.max(0, cacheControl), MAX_MAX_AGE) / 1000,
592-
);
579+
let { cacheControl } = context.options;
580+
581+
// Normalize cacheControl to object
582+
if (typeof cacheControl === "string") {
583+
setResponseHeader(res, "Cache-Control", cacheControl);
584+
} else if (hasCacheImmutable && extra.immutable) {
585+
cacheControl = { immutable: true };
586+
} else if (typeof cacheControl === "boolean") {
587+
cacheControl = { maxAge: MAX_MAX_AGE };
588+
} else if (typeof cacheControl === "number") {
589+
cacheControl = {
590+
maxAge: Math.min(Math.max(0, cacheControl), MAX_MAX_AGE),
591+
};
592+
}
593593

594-
cacheControlValue = `public, max-age=${maxAge}`;
595-
} else if (typeof cacheControl === "string") {
596-
cacheControlValue = cacheControl;
597-
} else {
598-
const maxAge = cacheControl.maxAge
594+
if (cacheControl && typeof cacheControl === "object") {
595+
const maxAge =
596+
cacheControl.maxAge !== undefined
599597
? Math.floor(
600-
Math.min(Math.max(0, cacheControl.maxAge), MAX_MAX_AGE) /
601-
1000,
598+
Math.min(Math.max(0, cacheControl.maxAge), MAX_MAX_AGE),
602599
)
603-
: MAX_MAX_AGE / 1000;
600+
: MAX_MAX_AGE;
604601

605-
cacheControlValue = `public, max-age=${maxAge}`;
602+
let cacheControlValue = `public, max-age=${Math.floor(maxAge / 1000)}`;
606603

607-
if (cacheControl.immutable && hasCacheImmutable) {
608-
cacheControlValue += ", immutable";
609-
}
604+
if (cacheControl.immutable && hasCacheImmutable) {
605+
cacheControlValue += ", immutable";
610606
}
611607

612608
setResponseHeader(res, "Cache-Control", cacheControlValue);

0 commit comments

Comments
 (0)