How to use fastify and protobuf
Create a simple plugin to manage binary data with protobuf
'use strict'
const fp = require ( 'fastify-plugin' )
const protobufjs = require ( 'protobufjs' )
function protobufjsSerializerPlugin ( 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'
} , async ( req , body , done ) => {
try {
const res = Package . decode ( body )
return res
} catch ( err ) {
done ( err )
}
} )
next ( )
}
module . exports = fp ( protobufjsSerializerPlugin , {
fastify : '>=3.x' ,
name : 'fastify-protobufjs-serializer'
} )
Define Fastify server basic and import our custom pluging for msgpack
'use strict'
const path = require ( 'path' )
const fastify = require ( 'fastify' ) ( {
logger : {
prettyPrint : true
}
} )
fastify . register ( require ( './fastify-protobufjs-serializer' ) , {
protoloadPath : path . join ( __dirname , 'schema' , 'package.proto' ) ,
messagePackage : 'Package'
} )
fastify . post ( '/decode' , ( req , reply ) => {
// http POST http://localhost:5000/decode Accept:application/x-protobuf Content-Type:application/x-protobuf @grpc\package-protobuf.dat
const body = req . body
return body
} )
fastify . get ( '/encode' , ( req , reply ) => {
// http http://localhost:5000/encode Accept:application/x-protobuf
reply . send ( {
name : "binari-encodings" ,
private : true ,
version : "1.0.0" ,
main : "index.js" ,
licence : "MIT" ,
value : 42
} )
} )
const start = async ( ) => {
try {
await fastify . listen ( 5000 )
} catch ( err ) {
fastify . log . error ( err )
process . exit ( 1 )
}
}
start ( )