Skip to content

Commit

Permalink
refactor: simplified header interpreter
Browse files Browse the repository at this point in the history
  • Loading branch information
arthurfiorette committed Jan 2, 2022
1 parent bafe1de commit e776f01
Showing 1 changed file with 33 additions and 37 deletions.
70 changes: 33 additions & 37 deletions src/header/interpreter.ts
Original file line number Diff line number Diff line change
@@ -1,53 +1,49 @@
import { parse } from 'cache-parser';
import { Header } from '../util/headers';
import type { HeaderInterpreter, HeadersInterpreter } from './types';
import type { HeadersInterpreter } from './types';

export const defaultHeaderInterpreter: HeadersInterpreter = (headers = {}) => {
if (Header.CacheControl in headers) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return interpretCacheControl(headers[Header.CacheControl]!, headers);
}

if (Header.Expires in headers) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return interpretExpires(headers[Header.Expires]!, headers);
}
export const defaultHeaderInterpreter: HeadersInterpreter = (headers) => {
if (!headers) return undefined;

return undefined;
};
const cacheControl = headers[Header.CacheControl];

const interpretExpires: HeaderInterpreter = (expires) => {
const milliseconds = Date.parse(expires) - Date.now();
return milliseconds >= 0 ? milliseconds : false;
};
if (cacheControl) {
const { noCache, noStore, mustRevalidate, maxAge, immutable } = parse(cacheControl);

const interpretCacheControl: HeaderInterpreter = (cacheControl, headers) => {
const { noCache, noStore, mustRevalidate, maxAge, immutable } = parse(cacheControl);
// Header told that this response should not be cached.
if (noCache || noStore) {
return false;
}

// Header told that this response should not be cached.
if (noCache || noStore) {
return false;
}
if (immutable) {
// 1 year is sufficient, as Infinity may cause more problems.
// It might not be the best way, but a year is better than none.
return 1000 * 60 * 60 * 24 * 365;
}

if (immutable) {
// 1 year is sufficient, as Infinity may cause more problems.
// It might not be the best way, but a year is better than none.
return 1000 * 60 * 60 * 24 * 365;
}
// Already out of date, for cache can be saved, but must be requested again
if (mustRevalidate) {
return 0;
}

// Already out of date, for cache can be saved, but must be requested again
if (mustRevalidate) {
return 0;
}
if (maxAge) {
const age = headers[Header.Age];

if (maxAge) {
const age = headers[Header.Age];
if (!age) {
return maxAge * 1000;
}

if (!age) {
return maxAge * 1000;
return (maxAge - Number(age)) * 1000;
}

return (maxAge - Number(age)) * 1000;
return undefined;
}

const expires = headers[Header.Expires];

if (expires) {
const milliseconds = Date.parse(expires) - Date.now();
return milliseconds >= 0 ? milliseconds : false;
}

return undefined;
Expand Down

0 comments on commit e776f01

Please sign in to comment.