-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
40 lines (32 loc) · 976 Bytes
/
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
'use strict'
const fp = require('fastify-plugin')
const protobufjs = require('protobufjs')
function fastifyProtobuf(fastify, options, next) {
const { protoloadPath, messagePackage } = options
const root = protobufjs.loadSync(protoloadPath)
const Package = root.lookupType(messagePackage)
fastify.register(require('fastify-accepts-serializer'), {
serializers: [
{
regex: /^application\/x-protobuf$/,
serializer: body => Package.encode(Package.create(body)).finish()
}
],
default: 'application/json'
})
fastify.addContentTypeParser('application/x-protobuf', {
parseAs: 'buffer'
}, (req, body, done) => {
try {
const res = Package.decode(body)
return res
} catch (err) {
done(err)
}
})
next()
}
module.exports = fp(fastifyProtobuf, {
fastify: '3.x',
name: 'fastify-protobufjs'
})