Skip to content

Instantly share code, notes, and snippets.

@kenriortega
Created May 16, 2021 17:09
Show Gist options
  • Save kenriortega/dd978c2aa830bf5746f656b4385903d3 to your computer and use it in GitHub Desktop.
Save kenriortega/dd978c2aa830bf5746f656b4385903d3 to your computer and use it in GitHub Desktop.
Protobuf.js and fastify

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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment