This repository was archived by the owner on Nov 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 648
Expand file tree
/
Copy pathlang-resolver.js
More file actions
58 lines (48 loc) · 1.46 KB
/
lang-resolver.js
File metadata and controls
58 lines (48 loc) · 1.46 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
const i18n = require('../lib/i18n')
const url = require('url')
const locales = Object.keys(i18n.locales)
var lowerLangRegion = {}
var lowerLang = {}
// Keep all the language/region and language in a object
// with property names in lowercases to resolve the lang code
locales.forEach((locale) => {
// map locale in lowercase
lowerLangRegion[locale.toLowerCase()] = locale
const lang = locale.split('-').shift().toLowerCase()
// The first lang for each locale is the default one
// to resolve when the region is missing
if (!lowerLang.hasOwnProperty(lang)) {
lowerLang[lang] = locale
}
})
function resolve(lang) {
var lower = lang.toLowerCase()
if (lowerLangRegion.hasOwnProperty(lower)) {
return lowerLangRegion[lower]
}
lower = lang.split('-').shift().toLowerCase()
if (lowerLang.hasOwnProperty(lower)) {
return lowerLang[lower]
}
return lang
}
function parseurl(req) {
return url.parse(req.url)
}
module.exports = function langResolver(req, res, next) {
if (req.query.lang) {
// resolving lang to lang-REGION when
// - cases does not match
// - region is missing
const rlang = resolve(req.query.lang)
// redirect only when the resolved lang exists and it is different
if (rlang && rlang !== req.query.lang) {
const parsedUrl = parseurl(req)
req.query.lang = rlang
return res.redirect(
url.format({ pathname: parsedUrl.pathname, query: req.query })
)
}
}
return next()
}