Separate client and server codes. Keep everything in one git repo for simplicity
[vchess.git] / client / src / utils / language.js
CommitLineData
625022fd
BA
1// TODO: adapt for client side https://stackoverflow.com/a/4079798
2// ==> Each translation file should be loaded dynamically
3// (each rules definition too, + modal welcome)
4
298c42e6
BA
5// Select a language based on browser preferences, or cookie
6module.exports = function(req, res)
7{
8 // If preferred language already set:
9 if (!!req.cookies["lang"])
10 return req.cookies["lang"];
11
12 // Else: search and set it
13 const supportedLang = ["en","es","fr"];
14 const langString = req.headers["accept-language"];
15 let langArray = langString
16 .replace(/;q=[0-9.]+/g, "") //priority
17 .replace(/-[A-Z]+/g, "") //region (skipped for now...)
18 .split(",") //may have some duplicates, but removal is too costly
19 let bestLang = "en"; //default: English
20 for (let lang of langArray)
21 {
22 if (supportedLang.includes(lang))
23 {
24 bestLang = lang;
25 break;
26 }
27 }
28 // Cookie expires in 183 days (expressed in milliseconds)
29 res.cookie('lang', bestLang, { maxAge: 183*24*3600*1000 });
30 return bestLang;
31}