Skip to content

Commit

Permalink
🔨 attempt to move csv url to slug.csv
Browse files Browse the repository at this point in the history
  • Loading branch information
danyx23 committed May 24, 2024
1 parent 3acd61e commit f600a8b
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 83 deletions.
117 changes: 85 additions & 32 deletions functions/grapher/[slug].ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { IRequestStrict, Router, error } from "itty-router"
import { fetchCsvForGrapher } from "../_common/grapherRenderer.js"
import { Env } from "./thumbnail/[slug].js"
export const onRequestGet: PagesFunction = async (context) => {
// Makes it so that if there's an error, we will just deliver the original page before the HTML rewrite.
// Only caveat is that redirects will not be taken into account for some reason; but on the other hand the worker is so simple that it's unlikely to fail.
Expand Down Expand Up @@ -74,37 +77,87 @@ export const onRequestGet: PagesFunction = async (context) => {
// In the case of the redirect, the browser will then request the new URL which will again be handled by this worker.
if (grapherPageResp.status !== 200) return grapherPageResp

const openGraphThumbnailUrl = `/grapher/thumbnail/${lowerCaseSlug}.png?imType=og${
url.search ? "&" + url.search.slice(1) : ""
}`
const twitterThumbnailUrl = `/grapher/thumbnail/${lowerCaseSlug}.png?imType=twitter${
url.search ? "&" + url.search.slice(1) : ""
}`

// Take the origin (e.g. https://ourworldindata.org) from the canonical URL, which should appear before the image elements.
// If we fail to capture the origin, we end up with relative image URLs, which should also be okay.
let origin = ""

// Rewrite the two meta tags that are used for a social media preview image.
const rewriter = new HTMLRewriter()
.on('meta[property="og:url"]', {
// Replace canonical URL, otherwise the preview image will not include the search parameters.
element: (element) => {
const canonicalUrl = element.getAttribute("content")
element.setAttribute("content", canonicalUrl + url.search)
origin = new URL(canonicalUrl).origin
},
})
.on('meta[property="og:image"]', {
element: (element) => {
element.setAttribute("content", origin + openGraphThumbnailUrl)
},
})
.on('meta[name="twitter:image"]', {
element: (element) => {
element.setAttribute("content", origin + twitterThumbnailUrl)
},
})
const handleGrapherPage = (): Response => {
const openGraphThumbnailUrl = `/grapher/thumbnail/${lowerCaseSlug}.png?imType=og${
url.search ? "&" + url.search.slice(1) : ""
}`
const twitterThumbnailUrl = `/grapher/thumbnail/${lowerCaseSlug}.png?imType=twitter${
url.search ? "&" + url.search.slice(1) : ""
}`

return rewriter.transform(grapherPageResp)
// Take the origin (e.g. https://ourworldindata.org) from the canonical URL, which should appear before the image elements.
// If we fail to capture the origin, we end up with relative image URLs, which should also be okay.
let origin = ""

// Rewrite the two meta tags that are used for a social media preview image.
const rewriter = new HTMLRewriter()
.on('meta[property="og:url"]', {
// Replace canonical URL, otherwise the preview image will not include the search parameters.
element: (element) => {
const canonicalUrl = element.getAttribute("content")
element.setAttribute("content", canonicalUrl + url.search)
origin = new URL(canonicalUrl).origin
},
})
.on('meta[property="og:image"]', {
element: (element) => {
element.setAttribute(
"content",
origin + openGraphThumbnailUrl
)
},
})
.on('meta[name="twitter:image"]', {
element: (element) => {
element.setAttribute(
"content",
origin + twitterThumbnailUrl
)
},
})

return rewriter.transform(grapherPageResp)
}

const shouldCache =
!url.searchParams.has("nocache") && context.request.url.endsWith(".csv")

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"))

const router = Router<IRequestStrict, [URL, Env, ExecutionContext]>()
router
.get(
"/grapher/:slug.csv",
async ({ params: { slug } }, { searchParams }, env) =>
fetchCsvForGrapher(slug, env)
)
.get(
"/grapher/:slug",
async ({ params: { slug } }, { searchParams }, env) =>
handleGrapherPage()
)
.all("*", () => error(404, "Route not defined"))
return router
.handle(request, url, { ...env, url }, context)
.then((resp: Response) => {
if (shouldCache) {
resp.headers.set(
"Cache-Control",
"public, s-maxage=3600, max-age=3600"
)
context.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))
}
51 changes: 0 additions & 51 deletions functions/grapher/csv/[slug].ts

This file was deleted.

0 comments on commit f600a8b

Please sign in to comment.