|
| 1 | +// Serves the RSS + sitemap feeds that the `turtle` service writes to the R2 |
| 2 | +// bucket bound as FEEDS (see wrangler.toml). The static site is generated by |
| 3 | +// scripts/build.js and is immutable per Pages deploy, so these dynamic feeds |
| 4 | +// can't live in stage/ — they're fetched from R2 on request instead. |
| 5 | +// |
| 6 | +// _headers rules do NOT apply to Function responses, so we set Cache-Control |
| 7 | +// here (600s, matching turtle's S3 CacheControl). Every other request falls |
| 8 | +// through via next() to the static asset pipeline, where _headers still applies. |
| 9 | + |
| 10 | +export async function onRequest( context ) { |
| 11 | + const { request, env, next } = context; |
| 12 | + const path = new URL( request.url ).pathname; |
| 13 | + |
| 14 | + let key = null; |
| 15 | + let fallbackType = 'application/xml'; |
| 16 | + |
| 17 | + if ( /^\/sitemap(\.[^/]+)?\.xml$/.test( path ) ) { |
| 18 | + // /sitemap.xml or /sitemap.<game>.xml |
| 19 | + key = path.slice( 1 ); |
| 20 | + } else if ( /^\/[^/]+\/rss$/.test( path ) ) { |
| 21 | + // /<game>/rss |
| 22 | + key = path.slice( 1 ); |
| 23 | + fallbackType = 'application/rss+xml'; |
| 24 | + } |
| 25 | + |
| 26 | + if ( !key ) { |
| 27 | + return next(); |
| 28 | + } |
| 29 | + |
| 30 | + const object = await env.FEEDS.get( key ); |
| 31 | + |
| 32 | + if ( !object ) { |
| 33 | + return new Response( 'Not found', { status: 404 } ); |
| 34 | + } |
| 35 | + |
| 36 | + return new Response( object.body, { |
| 37 | + headers: { |
| 38 | + 'Content-Type': object.httpMetadata?.contentType || fallbackType, |
| 39 | + 'Cache-Control': 'public, max-age=600', |
| 40 | + }, |
| 41 | + } ); |
| 42 | +} |
0 commit comments