-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathindex.js
62 lines (50 loc) · 1.64 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
'use strict'
const accepts = require('accepts')
const fp = require('fastify-plugin')
const acceptsObjectSymbol = Symbol('acceptsObject')
const methodNames = [
'charset', 'charsets',
'encoding', 'encodings',
'language', 'languages',
'type', 'types'
]
function acceptsMethod () {
if (!this.raw[acceptsObjectSymbol]) {
this.raw[acceptsObjectSymbol] = accepts(this.raw)
}
return this.raw[acceptsObjectSymbol]
}
function replyAcceptMethod () {
if (!this.request[acceptsObjectSymbol]) {
this.request[acceptsObjectSymbol] = accepts(this.request.raw)
}
return this.request[acceptsObjectSymbol]
}
function fastifyAccepts (fastify, options, done) {
fastify.decorateRequest('accepts', acceptsMethod)
methodNames.forEach(methodName => {
fastify.decorateRequest(methodName, function (arr) {
const acceptsObject = this.accepts()
if (arguments.length === 0) return acceptsObject[methodName]()
return acceptsObject[methodName](arr)
})
})
if (options.decorateReply === true) {
fastify.decorateReply('requestAccepts', replyAcceptMethod)
methodNames.forEach(methodName => {
const capitalizedMethodName = methodName.replace(/(?:^|\s)\S/gu, a => a.toUpperCase())
fastify.decorateReply('request' + capitalizedMethodName, function (arr) {
const acceptsObject = this.requestAccepts()
if (arguments.length === 0) return acceptsObject[methodName]()
return acceptsObject[methodName](arr)
})
})
}
done()
}
module.exports = fp(fastifyAccepts, {
fastify: '5.x',
name: '@fastify/accepts'
})
module.exports.default = fastifyAccepts
module.exports.fastifyAccepts = fastifyAccepts