-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
81 lines (74 loc) · 2.31 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
const fp = require('fastify-plugin')
const {
sendPayloadToTreblle,
generateFieldsToMask,
maskSensitiveValues,
generateTrebllePayload,
getResponsePayload,
} = require('@treblle/utils')
const { version: sdkVersion } = require('./package.json')
async function treblleFastify(
fastify,
{
apiKey = process.env.TREBLLE_API_KEY,
projectId = process.env.TREBLLE_PROJECT_ID,
additionalFieldsToMask = [],
}
) {
fastify.decorateReply('payload', null)
fastify.addHook('onSend', (request, reply, payload, done) => {
reply.payload = payload
done()
})
fastify.addHook('onResponse', (request, reply, done) => {
done()
let errors = []
const body = request.body ?? {}
const params = request.params
const query = request.query
const requestPayload = { ...body, ...params, ...query }
const fieldsToMask = generateFieldsToMask(additionalFieldsToMask)
const maskedRequestPayload = maskSensitiveValues(requestPayload, fieldsToMask)
const protocol = `${request.protocol}/${request.raw.httpVersion}`
const { payload: maskedResponseBody, error: invalidResponseBodyError } = getResponsePayload(
reply.payload,
fieldsToMask
)
if (invalidResponseBodyError) {
errors.push(invalidResponseBodyError)
}
const trebllePayload = generateTrebllePayload(
{ api_key: apiKey, project_id: projectId, sdk: 'fastify', version: sdkVersion },
{
server: {
protocol,
ip: fastify.server.address().address,
},
request: {
ip: request.ip,
url: `${request.protocol}://${request.headers['host']}${request.url}`,
user_agent: request.headers['user-agent'],
method: request.method,
headers: maskSensitiveValues(request.headers, fieldsToMask),
body: maskedRequestPayload,
},
response: {
headers: maskSensitiveValues(reply.getHeaders(), fieldsToMask),
code: reply.statusCode,
size: reply.getHeader('content-length'),
load_time: reply.getResponseTime(),
body: maskedResponseBody ?? null,
},
errors,
}
)
try {
sendPayloadToTreblle(trebllePayload, apiKey)
} catch (error) {
console.log(error)
}
})
}
module.exports = fp(treblleFastify, {
name: 'treblle-fastify',
})