5.3.0 • Published 4 months ago

@fastify/accepts-serializer v5.3.0

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

@fastify/accepts-serializer

CI npm version js-standard-style

Serialize according to the Accept header. Supports Fastify versions ^4.0.0

Install

npm i @fastify/accepts-serializer

Usage

const protobuf = require('protobufjs')
const YAML = require('yamljs')
const msgpack = require('msgpack5')()

const root = protobuf.loadSync('test/awesome.proto')
const AwesomeMessage = root.lookupType('awesomepackage.AwesomeMessage')

let fastify = require('fastify')()

// Global serializers
fastify.register(require('@fastify/accepts-serializer'), {
  serializers: [
    {
      regex: /^application\/yaml$/,
      serializer: body => YAML.stringify(body)
    },
    {
      regex: /^application\/x-msgpack$/,
      serializer: body => msgpack.encode(body)
    }
  ],
  default: 'application/yaml' // MIME type used if Accept header don't match anything
})

// Per-router serializers
const config = {
  serializers: [
    {
      regex: /^application\/x-protobuf$/,
      serializer: body => AwesomeMessage.encode(AwesomeMessage.create(body)).finish()
    }
  ]
}

fastify.get('/request', { config }, function (req, reply) {
  reply.send({pippo: 'pluto'})
})

Behaviour

For each route, a SerializerManager is defined, which has both per-route and global serializer definitions.

The MIME type application/json is always handled by fastify if no serializer is registered for that MIME type.

If no default key is specified in configuration, all requests with an unknown Accept header will be replied to with a 406 response (a boom error is used).

5.3.0

4 months ago

5.2.0

1 year ago

5.1.0

2 years ago

5.0.0

2 years ago

4.0.1

2 years ago

4.0.0

2 years ago