forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdetect-language.js
60 lines (52 loc) · 2.06 KB
/
detect-language.js
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
import languages, { languageKeys } from '../lib/languages.js'
import parser from 'accept-language-parser'
const chineseRegions = ['CN', 'HK']
// This value is replicated in two places! See <LanguagePicker/> component.
// Note, the only reason this is exported is to benefit the tests.
export const PREFERRED_LOCALE_COOKIE_NAME = 'preferredlang'
function translationExists(language) {
if (language.code === 'zh') {
return chineseRegions.includes(language.region)
}
return languageKeys.includes(language.code)
}
function getLanguageCode(language) {
return language.code === 'zh' && chineseRegions.includes(language.region) ? 'cn' : language.code
}
function getUserLanguage(browserLanguages) {
try {
let numTopPreferences = 1
for (let lang = 0; lang < browserLanguages.length; lang++) {
// If language has multiple regions, Chrome adds the non-region language to list
if (lang > 0 && browserLanguages[lang].code !== browserLanguages[lang - 1].code)
numTopPreferences++
if (translationExists(browserLanguages[lang]) && numTopPreferences < 3) {
return getLanguageCode(browserLanguages[lang])
}
}
} catch {
return undefined
}
}
function getUserLanguageFromCookie(req) {
const value = req.cookies[PREFERRED_LOCALE_COOKIE_NAME]
// But if it's a WIP language, reject it.
if (value && languages[value] && !languages[value].wip) {
return value
}
}
// determine language code from a path. Default to en if no valid match
export function getLanguageCodeFromPath(path) {
const maybeLanguage = (path.split('/')[path.startsWith('/_next/data/') ? 4 : 1] || '').slice(0, 2)
return languageKeys.includes(maybeLanguage) ? maybeLanguage : 'en'
}
export default function detectLanguage(req, res, next) {
req.language = getLanguageCodeFromPath(req.path)
// Detecting browser language by user preference
req.userLanguage = getUserLanguageFromCookie(req)
if (!req.userLanguage) {
const browserLanguages = parser.parse(req.headers['accept-language'])
req.userLanguage = getUserLanguage(browserLanguages)
}
return next()
}