-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathplugin.js
42 lines (31 loc) · 1.07 KB
/
plugin.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
'use strict'
const fp = require('fastify-plugin')
const { defaultOptions, supportedParsers } = require('./default-options')
const fastifyLP = (fastify, opts, next) => {
const options = Object.assign({}, defaultOptions, opts)
fastify.decorateRequest('detectedLng', options.fallbackLng)
const parsers = options.order
if (!Array.isArray(parsers)) {
return next(new Error('options.order has to be an array'))
}
if (!parsers.length) {
return next(new Error('options.order has to contain at least one parser.'))
}
parsers.map(name => {
if (supportedParsers.indexOf(name) === -1) {
return next(new Error(`${name} is not a valid language parser`))
}
if (options.order.indexOf(name) !== options.order.lastIndexOf(name)) {
return next(new Error(`${name} parser found multiple times in order option. Try scope your routes instead.`))
}
return fastify.addHook(
'preHandler',
require('./parser')(name, options)
)
})
next()
}
module.exports = fp(fastifyLP, {
fastify: '>=3.0.0',
name: 'fastify-language-parser'
})