forked from OmerTu/GoogleHomeKodi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbroker.js
60 lines (43 loc) · 1.52 KB
/
broker.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
'use strict'; // eslint-disable-line strict
const Helper = require('./helpers.js');
let lastUsedLanguage = ``;
let localizedPhrases = null;
const testRegexNamedGroupesFeature = () => {
let match = false;
try {
match = `named group test`.match(`(?<group>test)`);
} catch (error) {
match = false;
}
if (!match) {
throw new Error(
`regex named groups test failed. ` +
`You need nodejs version 10 or higher for the broker to work!`);
}
};
exports.processRequest = (request, response) => {
testRegexNamedGroupesFeature();
let phrase = request.query.phrase.toLowerCase();
let language = request.query.lang || `en`;
if (lastUsedLanguage !== language) {
// reload lang file if language has changed
localizedPhrases = require(`./broker/${language}.json`);
lastUsedLanguage = language;
}
console.log(`Broker processing phrase: '${phrase}' (${language})`);
for (let key in localizedPhrases) {
let match = phrase.match(`^${localizedPhrases[key]}`);
if (match) {
// copy named groups to request.query
for (let g in match.groups) {
if (match.groups[g]) {
request.query[g] = match.groups[g];
}
}
let endpoint = key.split(`:`, 1)[0];
// call original handler
return Helper[endpoint](request, response);
}
}
throw new Error(`Broker unknown phrase: '${phrase}' (${language})`);
};