From 1c769894d773ef6e265638badc6207b9c845df17 Mon Sep 17 00:00:00 2001 From: Claas Augner Date: Fri, 17 May 2024 19:01:28 -0400 Subject: [PATCH] feat(cloud-function): redirect capitalization --- cloud-function/src/app.ts | 5 +++ .../middlewares/redirect-capitalization.ts | 33 +++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 cloud-function/src/middlewares/redirect-capitalization.ts diff --git a/cloud-function/src/app.ts b/cloud-function/src/app.ts index 66019a394427..764c55e485b4 100644 --- a/cloud-function/src/app.ts +++ b/cloud-function/src/app.ts @@ -22,6 +22,7 @@ import { resolveRunnerHtml } from "./middlewares/resolve-runner-html.js"; import { proxyRunner } from "./handlers/proxy-runner.js"; import { stripForwardedHostHeaders } from "./middlewares/stripForwardedHostHeaders.js"; import { proxyPong } from "./handlers/proxy-pong.js"; +import { redirectCapitalization } from "./middlewares/redirect-capitalization.js"; const router = Router(); router.use(stripForwardedHostHeaders); @@ -60,6 +61,7 @@ router.get( router.get( `/[^/]+/docs/*/*.(${ANY_ATTACHMENT_EXT.join("|")})`, requireOrigin(Origin.main, Origin.liveSamples, Origin.play), + redirectCapitalization, resolveIndexHTML, proxyContent ); @@ -70,6 +72,7 @@ router.get( redirectLocale, redirectTrailingSlash, redirectMovedPages, + redirectCapitalization, resolveIndexHTML, proxyContent ); @@ -78,6 +81,7 @@ router.get( requireOrigin(Origin.main), redirectLocale, redirectEnforceTrailingSlash, + redirectCapitalization, resolveIndexHTML, proxyContent ); @@ -93,6 +97,7 @@ router.get( redirectFundamental, redirectLocale, redirectTrailingSlash, + redirectCapitalization, resolveIndexHTML, proxyContent ); diff --git a/cloud-function/src/middlewares/redirect-capitalization.ts b/cloud-function/src/middlewares/redirect-capitalization.ts new file mode 100644 index 000000000000..16d8c6489bc4 --- /dev/null +++ b/cloud-function/src/middlewares/redirect-capitalization.ts @@ -0,0 +1,33 @@ +import { NextFunction, Request, Response } from "express"; + +import { THIRTY_DAYS } from "../constants.js"; +import { redirect } from "../utils.js"; +import { Source, sourceUri } from "../env.js"; +import { slugToFolder } from "@yari-internal/slug-utils"; + +const target = sourceUri(Source.content); + +export async function redirectCapitalization( + req: Request, + res: Response, + next: NextFunction +) { + const url = new URL(req.url, `${req.protocol}://${req.headers.host}`); + + const requestURI = url.pathname; + const qs = url.search; + + const metadataURL = `${target}${slugToFolder(requestURI).slice(1).toLowerCase()}/metadata.json`; + const tryMetadata = await fetch(metadataURL); + if (tryMetadata.ok) { + const metadata = await tryMetadata.json(); + const mdn_url = metadata.mdn_url; + if (mdn_url && mdn_url !== requestURI) { + return redirect(res, mdn_url + qs, { + cacheControlSeconds: THIRTY_DAYS, + }); + } + } + + next(); +}