/
index.js
108 lines (78 loc) · 2.57 KB
/
index.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
class expressI18 {
// Constructor
constructor(app, data = {}) {
// Insert App
this.app = app;
// Lodash Module
const _ = require('lodash');
this.data = _.defaultsDeep({}, data, {
// Vars Session Names
cfg: {
varsSession: {
sessionLang: 'sessionLang',
userLang: 'userLang',
nowLang: 'nowLang'
},
// URLs
urls: {
setLang: '/setLang'
},
},
// Get CSRF Token
getCsrfToken: function (req, res) {
return {
now: '',
server: ''
};
}
});
// Prepare Module
const apiPrepare = require('./api');
this.module = new apiPrepare(this.data.cfg);
// Complete
return this;
}
// Get Module
getModule() { return this.module; }
// Insert Express
insert(checkIsUser) {
const tinyThis = this;
return async (req, res, next) => {
// Is User
let isUser = false;
// Check Is User
if (typeof checkIsUser === "function") { isUser = await checkIsUser(req, res); }
else if (typeof checkIsUser === "boolean") { isUser = checkIsUser; }
// Get User Lang
const userLang = tinyThis.module.getUserLang({
session: req.session[tinyThis.data.cfg.varsSession.sessionLang],
user: req.session[tinyThis.data.cfg.varsSession.userLang],
isUser: isUser
});
// Set Session
req.session[tinyThis.data.cfg.varsSession.sessionLang] = userLang.session;
req.session[tinyThis.data.cfg.varsSession.userLang] = userLang.user;
req.session[tinyThis.data.cfg.varsSession.nowLang] = userLang.now;
// Module
req.i18 = tinyThis.module;
req.i18IsUser = userLang.isUser;
// Complete
next();
return;
};
}
// Start Module
start() {
// Get This
const tinyThis = this;
// Set Cookie
this.app.post(this.data.cfg.urls.setLang, async function (req, res) {
// Send Request
const csrfToken = await tinyThis.data.getCsrfToken(req, res);
req.i18.setLang.apply(req.i18, [req, res, csrfToken]);
// Complete
return;
});
}
};
module.exports = expressI18;