How to use fastify and msgpack
Create a simple plugin to manage binary data with msgpack
'use strict'
const fp = require ( 'fastify-plugin' )
const msgpack = require ( '@msgpack/msgpack' )
function msgpackSerializerPlugin ( fastify , options , next ) {
fastify . register ( require ( 'fastify-accepts-serializer' ) , {
serializers : [
{
regex : / ^ a p p l i c a t i o n \/ m s g p a c k $ / ,
serializer : body => Buffer . from ( msgpack . encode ( body ) )
}
] ,
default : 'application/json'
} )
fastify . addContentTypeParser ( 'application/msgpack' , {
parseAs : 'buffer'
} , async ( req , body , done ) => {
try {
const res = msgpack . decode ( body )
return res
} catch ( err ) {
done ( err )
}
} )
next ( )
}
module . exports = fp ( msgpackSerializerPlugin , {
fastify : '>=3.x' ,
name : 'fastify-msgpack-serializer'
} )
Define Fastify server basic and import our custom pluging for msgpack
'use strict'
const fastify = require ( 'fastify' ) ( {
logger : {
prettyPrint : true
}
} )
// custom plugin
fastify . register ( require ( './fastify-msgpack-serializer' ) )
fastify . post ( '/decode' , ( req , reply ) => {
// http POST http://localhost:5000/decode Accept:application/msgpack Content-Type:application/msgpack @msgpack\package-msgpack.dat
const body = req . body
return body
} )
fastify . get ( '/encode' , ( req , reply ) => {
// http http://localhost:5000/encode Accept:application/msgpack
reply . send ( { hello : 'MNTD en vivo' } )
} )
const start = async ( ) => {
try {
await fastify . listen ( 5000 )
} catch ( err ) {
fastify . log . error ( err )
process . exit ( 1 )
}
}
start ( )