Skip to content

Instantly share code, notes, and snippets.

@mystix
Forked from richardscarrott/worker.ts
Created April 28, 2025 14:20
Show Gist options
  • Save mystix/0d8af3ca7e73ded4d6385ac4cf28649a to your computer and use it in GitHub Desktop.
Save mystix/0d8af3ca7e73ded4d6385ac4cf28649a to your computer and use it in GitHub Desktop.

Revisions

  1. @richardscarrott richardscarrott revised this gist Aug 25, 2023. 1 changed file with 12 additions and 9 deletions.
    21 changes: 12 additions & 9 deletions worker.ts
    Original file line number Diff line number Diff line change
    @@ -32,6 +32,8 @@ const handleRequest = async (request: Request, env: {}, ctx: ExecutionContext):
    }
    const result = await response.json();

    await sleep(2000);

    return new Response(
    `
    <!doctype html>
    @@ -41,6 +43,7 @@ const handleRequest = async (request: Request, env: {}, ctx: ExecutionContext):
    </head>
    <body>
    <h1>Success</h1>
    <div>0.0.2</div>
    <div>${new Date().toString()}</div>
    <pre>${JSON.stringify(result, null, 2)}</pre>
    </body>
    @@ -49,28 +52,28 @@ const handleRequest = async (request: Request, env: {}, ctx: ExecutionContext):
    {
    headers: {
    'content-type': 'text/html',
    'CDN-Cache-Control': 'max-age=20, stale-while-revalidate=10',
    'x-timestamp': String(toSeconds(new Date())),
    'cache-control': 'no-cache, no-store, must-revalidate',
    'cdn-cache-control': 'max-age=14400, stale-while-revalidate=10',
    },
    }
    );
    };

    const shouldRevalidate = (cachedResponse: Response) => {
    const timestampHeader = cachedResponse.headers.get('x-timestamp');
    const cacheControlHeader = cachedResponse.headers.get('CDN-Cache-Control');
    if (!timestampHeader || !cacheControlHeader) {
    const ageHeader = cachedResponse.headers.get('age');
    const cacheControlHeader = cachedResponse.headers.get('cdn-cache-control');
    if (!ageHeader || !cacheControlHeader) {
    return false;
    }
    const staleWhileRevalidate = parse(cacheControlHeader)['stale-while-revalidate'];
    if (typeof staleWhileRevalidate === 'undefined') {
    return false;
    }
    const timestamp = Number(timestampHeader);
    if (Number.isNaN(timestamp)) {
    const age = Number(ageHeader);
    if (Number.isNaN(age)) {
    return false;
    }
    return timestamp + staleWhileRevalidate < toSeconds(new Date());
    return age > staleWhileRevalidate;
    };

    const toSeconds = (date: Date) => Math.floor(date.valueOf() / 1000);
    const sleep = (duration: number) => new Promise((resolve) => setTimeout(resolve, duration));
  2. @richardscarrott richardscarrott revised this gist Aug 25, 2023. 1 changed file with 0 additions and 1 deletion.
    1 change: 0 additions & 1 deletion worker.ts
    Original file line number Diff line number Diff line change
    @@ -59,7 +59,6 @@ const handleRequest = async (request: Request, env: {}, ctx: ExecutionContext):
    const shouldRevalidate = (cachedResponse: Response) => {
    const timestampHeader = cachedResponse.headers.get('x-timestamp');
    const cacheControlHeader = cachedResponse.headers.get('CDN-Cache-Control');
    console.log('headers', timestampHeader, cacheControlHeader);
    if (!timestampHeader || !cacheControlHeader) {
    return false;
    }
  3. @richardscarrott richardscarrott revised this gist Aug 25, 2023. 1 changed file with 0 additions and 3 deletions.
    3 changes: 0 additions & 3 deletions worker.ts
    Original file line number Diff line number Diff line change
    @@ -61,17 +61,14 @@ const shouldRevalidate = (cachedResponse: Response) => {
    const cacheControlHeader = cachedResponse.headers.get('CDN-Cache-Control');
    console.log('headers', timestampHeader, cacheControlHeader);
    if (!timestampHeader || !cacheControlHeader) {
    console.log('No header found');
    return false;
    }
    const staleWhileRevalidate = parse(cacheControlHeader)['stale-while-revalidate'];
    if (typeof staleWhileRevalidate === 'undefined') {
    console.log('No stale while revalidate found');
    return false;
    }
    const timestamp = Number(timestampHeader);
    if (Number.isNaN(timestamp)) {
    console.log('No timestamp found');
    return false;
    }
    return timestamp + staleWhileRevalidate < toSeconds(new Date());
  4. @richardscarrott richardscarrott revised this gist Aug 25, 2023. 1 changed file with 54 additions and 54 deletions.
    108 changes: 54 additions & 54 deletions worker.ts
    Original file line number Diff line number Diff line change
    @@ -1,39 +1,39 @@
    import { parse } from 'cache-control-parser';

    export default {
    async fetch(request: Request, env: {}, ctx: ExecutionContext): Promise<Response> {
    try {
    const cache = await caches.default;
    const cachedResponse = await cache.match(request);
    if (cachedResponse) {
    console.log('Cache: HIT');
    if (shouldRevalidate(cachedResponse)) {
    console.log('Cache: REVALIDATE');
    ctx.waitUntil(handleRequest(request, env, ctx).then((response) => cache.put(request, response.clone())));
    }
    return cachedResponse;
    }
    console.log('Cache: MISS');
    const response = await handleRequest(request, env, ctx);
    ctx.waitUntil(cache.put(request, response.clone()));
    return response;
    } catch (ex) {
    console.error(ex);
    return new Response('Internal server error', { status: 500 });
    }
    },
    async fetch(request: Request, env: {}, ctx: ExecutionContext): Promise<Response> {
    try {
    const cache = await caches.default;
    const cachedResponse = await cache.match(request);
    if (cachedResponse) {
    console.log('Cache: HIT');
    if (shouldRevalidate(cachedResponse)) {
    console.log('Cache: REVALIDATE');
    ctx.waitUntil(handleRequest(request, env, ctx).then((response) => cache.put(request, response.clone())));
    }
    return cachedResponse;
    }
    console.log('Cache: MISS');
    const response = await handleRequest(request, env, ctx);
    ctx.waitUntil(cache.put(request, response.clone()));
    return response;
    } catch (ex) {
    console.error(ex);
    return new Response('Internal server error', { status: 500 });
    }
    },
    };

    // e.g. Remix handler
    const handleRequest = async (request: Request, env: {}, ctx: ExecutionContext): Promise<Response> => {
    const response = await fetch('https://swapi.dev/api/people/1/');
    if (!response.ok) {
    return new Response(JSON.stringify({ error: `${response.status}: ${response.statusText}` }), { status: 500 });
    }
    const result = await response.json();
    const response = await fetch('https://swapi.dev/api/people/1/');
    if (!response.ok) {
    return new Response(JSON.stringify({ error: `${response.status}: ${response.statusText}` }), { status: 500 });
    }
    const result = await response.json();

    return new Response(
    `
    return new Response(
    `
    <!doctype html>
    <html>
    <head>
    @@ -46,35 +46,35 @@ const handleRequest = async (request: Request, env: {}, ctx: ExecutionContext):
    </body>
    </html>
    `,
    {
    headers: {
    'content-type': 'text/html',
    'CDN-Cache-Control': 'max-age=20, stale-while-revalidate=10',
    'x-timestamp': String(toSeconds(new Date())),
    },
    }
    );
    {
    headers: {
    'content-type': 'text/html',
    'CDN-Cache-Control': 'max-age=20, stale-while-revalidate=10',
    'x-timestamp': String(toSeconds(new Date())),
    },
    }
    );
    };

    const shouldRevalidate = (cachedResponse: Response) => {
    const timestampHeader = cachedResponse.headers.get('x-timestamp');
    const cacheControlHeader = cachedResponse.headers.get('CDN-Cache-Control');
    console.log('headers', timestampHeader, cacheControlHeader);
    if (!timestampHeader || !cacheControlHeader) {
    console.log('No header found');
    return false;
    }
    const staleWhileRevalidate = parse(cacheControlHeader)['stale-while-revalidate'];
    if (typeof staleWhileRevalidate === 'undefined') {
    console.log('No stale while revalidate found');
    return false;
    }
    const timestamp = Number(timestampHeader);
    if (Number.isNaN(timestamp)) {
    console.log('No timestamp found');
    return false;
    }
    return timestamp + staleWhileRevalidate < toSeconds(new Date());
    const timestampHeader = cachedResponse.headers.get('x-timestamp');
    const cacheControlHeader = cachedResponse.headers.get('CDN-Cache-Control');
    console.log('headers', timestampHeader, cacheControlHeader);
    if (!timestampHeader || !cacheControlHeader) {
    console.log('No header found');
    return false;
    }
    const staleWhileRevalidate = parse(cacheControlHeader)['stale-while-revalidate'];
    if (typeof staleWhileRevalidate === 'undefined') {
    console.log('No stale while revalidate found');
    return false;
    }
    const timestamp = Number(timestampHeader);
    if (Number.isNaN(timestamp)) {
    console.log('No timestamp found');
    return false;
    }
    return timestamp + staleWhileRevalidate < toSeconds(new Date());
    };

    const toSeconds = (date: Date) => Math.floor(date.valueOf() / 1000);
  5. @richardscarrott richardscarrott created this gist Aug 25, 2023.
    80 changes: 80 additions & 0 deletions worker.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,80 @@
    import { parse } from 'cache-control-parser';

    export default {
    async fetch(request: Request, env: {}, ctx: ExecutionContext): Promise<Response> {
    try {
    const cache = await caches.default;
    const cachedResponse = await cache.match(request);
    if (cachedResponse) {
    console.log('Cache: HIT');
    if (shouldRevalidate(cachedResponse)) {
    console.log('Cache: REVALIDATE');
    ctx.waitUntil(handleRequest(request, env, ctx).then((response) => cache.put(request, response.clone())));
    }
    return cachedResponse;
    }
    console.log('Cache: MISS');
    const response = await handleRequest(request, env, ctx);
    ctx.waitUntil(cache.put(request, response.clone()));
    return response;
    } catch (ex) {
    console.error(ex);
    return new Response('Internal server error', { status: 500 });
    }
    },
    };

    // e.g. Remix handler
    const handleRequest = async (request: Request, env: {}, ctx: ExecutionContext): Promise<Response> => {
    const response = await fetch('https://swapi.dev/api/people/1/');
    if (!response.ok) {
    return new Response(JSON.stringify({ error: `${response.status}: ${response.statusText}` }), { status: 500 });
    }
    const result = await response.json();

    return new Response(
    `
    <!doctype html>
    <html>
    <head>
    <title>Hello world</title>
    </head>
    <body>
    <h1>Success</h1>
    <div>${new Date().toString()}</div>
    <pre>${JSON.stringify(result, null, 2)}</pre>
    </body>
    </html>
    `,
    {
    headers: {
    'content-type': 'text/html',
    'CDN-Cache-Control': 'max-age=20, stale-while-revalidate=10',
    'x-timestamp': String(toSeconds(new Date())),
    },
    }
    );
    };

    const shouldRevalidate = (cachedResponse: Response) => {
    const timestampHeader = cachedResponse.headers.get('x-timestamp');
    const cacheControlHeader = cachedResponse.headers.get('CDN-Cache-Control');
    console.log('headers', timestampHeader, cacheControlHeader);
    if (!timestampHeader || !cacheControlHeader) {
    console.log('No header found');
    return false;
    }
    const staleWhileRevalidate = parse(cacheControlHeader)['stale-while-revalidate'];
    if (typeof staleWhileRevalidate === 'undefined') {
    console.log('No stale while revalidate found');
    return false;
    }
    const timestamp = Number(timestampHeader);
    if (Number.isNaN(timestamp)) {
    console.log('No timestamp found');
    return false;
    }
    return timestamp + staleWhileRevalidate < toSeconds(new Date());
    };

    const toSeconds = (date: Date) => Math.floor(date.valueOf() / 1000);