Repository navigation
Expand file tree
/
Copy pathcloudflare-worker.js
More file actions
67 lines (58 loc) · 1.63 KB
/
Copy pathcloudflare-worker.js
File metadata and controls
67 lines (58 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const DEBUG = false;
const DEFAULT_LANGUAGE = "en";
const PROJECT_TOKEN = "YOUR-PROJECT-TOKEN";
const ENVIRONMENT = "_latest";
const BASE_URL = "https://simplelocalize.github.io/simplelocalize-cloudflare-workers";
addEventListener('fetch', event => {
event.respondWith(handleEvent(event));
});
async function handleEvent(event) {
const url = new URL(event.request.url);
const pathname = url.pathname;
const fetchOptions = {
cacheControl: {
bypassCache: DEBUG,
},
};
try {
const languageKey = url.searchParams.get('lang') ?? DEFAULT_LANGUAGE;
const translations = await getTranslations(languageKey);
const originalContentAtPath = await fetch(BASE_URL + pathname, fetchOptions);
return new HTMLRewriter()
.on('[data-i18n-key]', new ElementHandler(translations))
.on('[lang]', new LangHandler(languageKey))
.transform(originalContentAtPath);
} catch (e) {
console.error(e);
return new Response(`Not found`, {
status: 404,
});
}
}
class ElementHandler {
constructor(countryStrings) {
this.languageTranslations = countryStrings;
}
element(element) {
const i18nKey = element.getAttribute('data-i18n-key');
if (i18nKey) {
const translation = this.languageTranslations[i18nKey];
if (translation) {
element.setInnerContent(translation);
}
}
}
}
class LangHandler {
constructor(language) {
this.language = language;
}
element(element) {
element.setAttribute('lang', this.language);
}
}
async function getTranslations(languageKey) {
return await fetch(`https://cdn.simplelocalize.io/${PROJECT_TOKEN}/${ENVIRONMENT}/${languageKey}`)
.then(response => response.json())
.catch(() => ({}));
}