Serve localized donation page

Signed-off-by: Alexander Borsuk <me@alex.bio>
This commit is contained in:
Alexander Borsuk 2022-11-20 19:16:32 +01:00
parent 3dc2b85125
commit f898e5d7e5
4 changed files with 54 additions and 0 deletions

View file

@ -6,6 +6,8 @@ This website is build with [Zola](https://www.getzola.org/) and Cloudflare Pages
Use `zola serve` for a local preview or `zola build` to generate static site in the `public` folder.
To test Clouldflare Functions locally, use `npx wrangler pages dev public` after doing `zola build`.
`npm i && npm run format` will pretty-format Markdown and scss.
Upgrade npm dependencies with `npm run upgrade`, make sure that you have installed `npm-check-updates` package.

39
functions/donate.ts Normal file
View file

@ -0,0 +1,39 @@
// Redirects users from the default en donate page to the appropriate localized version.
interface Env {
KV: KVNamespace;
}
// TODO: Detect if donation page already has translation in resources automatically,
// without hard-coded list
const localizedLanguages = ['ru', 'it', 'tr'];
// To parse accept-language like this:
// fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5
// en-AU,en;q=0.8,be;q=0.6,ru;q=0.4,uk;q=0.2
const langCodeRegex = /[a-z]{2}/g;
// Returns user's preferred languages: ["en", "be", "ru"]
function extractLanguageList(acceptLanguage: string): string[] {
const langs = acceptLanguage.match(langCodeRegex);
return [...new Set(langs)]; // Filter duplicates.
}
// Should be invoked only for /donate or /donate/ routes
export const onRequest: PagesFunction<Env> = async (context) => {
console.log('Donate handler hit url:' + context.request.url);
const acceptLanguage = context.request.headers.get('accept-language');
if (acceptLanguage) {
// Is there a localized version?
const languages = extractLanguageList(acceptLanguage);
const filtered = localizedLanguages.filter(lang => languages.includes(lang));
if (filtered.length) {
const url = new URL(context.request.url);
console.log('Old pathname: ' + url.pathname);
url.pathname = '/' + filtered[0] + url.pathname;
return context.env.ASSETS.fetch(url);
}
}
// Return default en version.
return context.env.ASSETS.fetch(context.request.url);
}

8
functions/tsconfig.json Normal file
View file

@ -0,0 +1,8 @@
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"lib": ["esnext"],
"types": ["@cloudflare/workers-types"]
}
}

5
static/_routes.json Normal file
View file

@ -0,0 +1,5 @@
{
"version": 1,
"include": ["/donate", "/donate/"],
"exclude": []
}