-
-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathlocales.js
More file actions
81 lines (61 loc) · 2.1 KB
/
Copy pathlocales.js
File metadata and controls
81 lines (61 loc) · 2.1 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const SUPPORTED_LOCALES = ['en', 'de']
const DEFAULT_LOCALE = 'en'
const LOCALE_COOKIE = 'bm_locale'
const isSupportedLocale = (value) =>
typeof value === 'string' && SUPPORTED_LOCALES.includes(value)
const parseCookieHeader = (cookieHeader, name) => {
if (!cookieHeader || typeof cookieHeader !== 'string') return null
const parts = cookieHeader.split(';')
for (const part of parts) {
const trimmed = part.trim()
const eq = trimmed.indexOf('=')
if (eq === -1) continue
const key = trimmed.slice(0, eq).trim()
if (key !== name) continue
return decodeURIComponent(trimmed.slice(eq + 1).trim())
}
return null
}
const parseAcceptLanguage = (header) => {
if (!header || typeof header !== 'string') return []
return header
.split(',')
.map((entry) => {
const [tag, ...params] = entry.split(';').map((p) => p.trim())
const qParam = params.find((p) => p.startsWith('q='))
const q = qParam ? parseFloat(qParam.slice(2)) : 1.0
return { tag, q: Number.isFinite(q) ? q : 1.0 }
})
.filter((entry) => entry.tag)
.sort((a, b) => b.q - a.q)
.map((entry) => entry.tag.toLowerCase())
}
const negotiateLocale = ({ user, cookieValue, acceptLanguage } = {}) => {
if (user && isSupportedLocale(user.locale)) return user.locale
if (isSupportedLocale(cookieValue)) return cookieValue
const ranked = parseAcceptLanguage(acceptLanguage)
for (const tag of ranked) {
const primary = tag.split('-')[0]
if (isSupportedLocale(primary)) return primary
}
return DEFAULT_LOCALE
}
const negotiateLocaleFromRequest = (req, user) => {
const cookieHeader = req && req.headers && req.headers.cookie ? req.headers.cookie : ''
const acceptLanguage = req && req.headers && req.headers['accept-language'] ? req.headers['accept-language'] : ''
return negotiateLocale({
user,
cookieValue: parseCookieHeader(cookieHeader, LOCALE_COOKIE),
acceptLanguage
})
}
module.exports = {
SUPPORTED_LOCALES,
DEFAULT_LOCALE,
LOCALE_COOKIE,
isSupportedLocale,
parseCookieHeader,
parseAcceptLanguage,
negotiateLocale,
negotiateLocaleFromRequest
}