-
-
Notifications
You must be signed in to change notification settings - Fork 228
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
🔨 attempt naive rendering of csv file in CF function
- Loading branch information
Showing
2 changed files
with
104 additions
and
14 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
import { fetchCsvForGrapher } from "../../_common/grapherRenderer.js" | ||
import { IRequestStrict, Router, error } from "itty-router" | ||
|
||
export interface Env { | ||
ASSETS: { | ||
fetch: typeof fetch | ||
} | ||
url: URL | ||
} | ||
|
||
const router = Router<IRequestStrict, [URL, Env, ExecutionContext]>() | ||
router | ||
.get( | ||
"/grapher/csv/:slug", | ||
async ({ params: { slug } }, { searchParams: _ }, env) => | ||
fetchCsvForGrapher(slug, env) | ||
) | ||
.all("*", () => error(404, "Route not defined")) | ||
|
||
export const onRequestGet: PagesFunction = async (ctx) => { | ||
const { request, env } = ctx | ||
|
||
const url = new URL(request.url) | ||
const shouldCache = !url.searchParams.has("nocache") | ||
|
||
const cache = caches.default | ||
if (shouldCache) { | ||
const maybeCached = await cache.match(request) | ||
if (maybeCached) return maybeCached | ||
} | ||
|
||
console.log("Handling", request.url, request.headers.get("User-Agent")) | ||
|
||
return router | ||
.handle(request, url, { ...env, url }, ctx) | ||
.then((resp: Response) => { | ||
if (shouldCache) { | ||
resp.headers.set( | ||
"Cache-Control", | ||
"public, s-maxage=3600, max-age=3600" | ||
) | ||
ctx.waitUntil(caches.default.put(request, resp.clone())) | ||
} else | ||
resp.headers.set( | ||
"Cache-Control", | ||
"public, s-maxage=0, max-age=0, must-revalidate" | ||
) | ||
return resp | ||
}) | ||
.catch((e) => error(500, e)) | ||
} |