Skip to content

Commit

Permalink
feat(cloud-function): redirect capitalization
Browse files Browse the repository at this point in the history
  • Loading branch information
caugner committed May 17, 2024
1 parent f8c0a29 commit 1c76989
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
5 changes: 5 additions & 0 deletions cloud-function/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -60,6 +61,7 @@ router.get(
router.get(
`/[^/]+/docs/*/*.(${ANY_ATTACHMENT_EXT.join("|")})`,
requireOrigin(Origin.main, Origin.liveSamples, Origin.play),
redirectCapitalization,
resolveIndexHTML,
proxyContent
);
Expand All @@ -70,6 +72,7 @@ router.get(
redirectLocale,
redirectTrailingSlash,
redirectMovedPages,
redirectCapitalization,
resolveIndexHTML,
proxyContent
);
Expand All @@ -78,6 +81,7 @@ router.get(
requireOrigin(Origin.main),
redirectLocale,
redirectEnforceTrailingSlash,
redirectCapitalization,
resolveIndexHTML,
proxyContent
);
Expand All @@ -93,6 +97,7 @@ router.get(
redirectFundamental,
redirectLocale,
redirectTrailingSlash,
redirectCapitalization,
resolveIndexHTML,
proxyContent
);
Expand Down
33 changes: 33 additions & 0 deletions cloud-function/src/middlewares/redirect-capitalization.ts
Original file line number Diff line number Diff line change
@@ -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();
}

0 comments on commit 1c76989

Please sign in to comment.