@fastify/accepts-serializer
TypeScript icon, indicating that this package has built-in type declarations

6.0.2 • Public • Published

@fastify/accepts-serializer

CI npm version neostandard javascript style

Serialize according to the Accept header.

Install

npm i @fastify/accepts-serializer

Compatibility

Plugin version Fastify version
^6.x ^5.x
^5.x ^4.x
^3.x ^3.x
^2.x ^2.x
^1.x ^1.x

Please note that if a Fastify version is out of support, then so are the corresponding version(s) of this plugin in the table above. See Fastify's LTS policy for more details.

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')

const 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).

License

Licensed under MIT.

Readme

Keywords

none

Package Sidebar

Install

npm i @fastify/accepts-serializer

Weekly Downloads

1,707

Version

6.0.2

License

MIT

Unpacked Size

24.3 kB

Total Files

14

Last publish

Collaborators

  • simoneb
  • delvedor
  • matteo.collina
  • jsumners
  • zekth
  • eomm
  • fox1t
  • airhorns
  • kibertoad
  • climba03003
  • galvez
  • simenb
  • gurgunday
  • metcoder95
  • jean-michelet
  • fdawgs