Skip to content

Instantly share code, notes, and snippets.

@kenriortega
Last active November 14, 2024 15:05
Show Gist options
  • Save kenriortega/ab94a28e3758130e18086dfef9831fb2 to your computer and use it in GitHub Desktop.
Save kenriortega/ab94a28e3758130e18086dfef9831fb2 to your computer and use it in GitHub Desktop.
MsgPack and Fastify

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: /^application\/msgpack$/,
                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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment