-
Notifications
You must be signed in to change notification settings - Fork 1
/
parser.js
68 lines (59 loc) · 1.8 KB
/
parser.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
'use strict'
function parserProducer (name, opts) {
const decorator = opts[`${name}Decorator`]
const key = opts[`${name}Key`]
const supportedLngs = opts.supportedLngs
if (name === 'header') return headerFactory(decorator, key, supportedLngs)
return commonFactory(decorator, key, supportedLngs)
}
function commonFactory (decorator, key, supportedLngs) {
if (supportedLngs.length === 0) return commonParser(decorator, key)
return commonParserWithSupportedCheck(decorator, key, supportedLngs)
}
function headerFactory (decorator, key, supportedLngs) {
if (supportedLngs.length === 0) return headerParser(decorator, key)
return headerParserWithSupportedCheck(decorator, key, supportedLngs)
}
function commonParser (decorator, key) {
return function (req, res, next) {
if (req[decorator] && req[decorator][key]) {
req.detectedLng = req[decorator][key]
}
next()
}
}
function commonParserWithSupportedCheck (decorator, key, supportedLngs) {
return function (req, res, next) {
if (req[decorator] && req[decorator][key] &&
supportedLngs.indexOf(req[decorator][key]) > -1
) {
req.detectedLng = req[decorator][key]
}
next()
}
}
function headerParser (decorator, key) {
return function (req, res, next) {
if (req[decorator] && req[decorator][key]) {
req.detectedLng = require('accept-language-parser').parse(
req[decorator][key]
)
}
next()
}
}
function headerParserWithSupportedCheck (decorator, key, supportedLngs) {
return function (req, res, next) {
if (req[decorator] && req[decorator][key]) {
const found = require('accept-language-parser').pick(
supportedLngs,
req[decorator][key]
)
if (found) {
req.detectedLng = found
}
}
next()
}
}
module.exports = parserProducer