Commit | Line | Data |
---|---|---|
298c42e6 BA |
1 | // Select a language based on browser preferences, or cookie |
2 | module.exports = function(req, res) | |
3 | { | |
4 | // If preferred language already set: | |
5 | if (!!req.cookies["lang"]) | |
6 | return req.cookies["lang"]; | |
7 | ||
8 | // Else: search and set it | |
9 | const supportedLang = ["en","es","fr"]; | |
10 | const langString = req.headers["accept-language"]; | |
11 | let langArray = langString | |
12 | .replace(/;q=[0-9.]+/g, "") //priority | |
13 | .replace(/-[A-Z]+/g, "") //region (skipped for now...) | |
14 | .split(",") //may have some duplicates, but removal is too costly | |
15 | let bestLang = "en"; //default: English | |
16 | for (let lang of langArray) | |
17 | { | |
18 | if (supportedLang.includes(lang)) | |
19 | { | |
20 | bestLang = lang; | |
21 | break; | |
22 | } | |
23 | } | |
24 | // Cookie expires in 183 days (expressed in milliseconds) | |
25 | res.cookie('lang', bestLang, { maxAge: 183*24*3600*1000 }); | |
26 | return bestLang; | |
27 | } |