Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/fastify/fastify-accepts-serializer
Serializer according to the accept header
https://github.com/fastify/fastify-accepts-serializer
fastify fastify-plugin
Last synced: 27 days ago
JSON representation
Serializer according to the accept header
- Host: GitHub
- URL: https://github.com/fastify/fastify-accepts-serializer
- Owner: fastify
- License: mit
- Created: 2017-08-02T17:53:56.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2024-04-13T09:33:30.000Z (7 months ago)
- Last Synced: 2024-05-13T05:09:30.225Z (6 months ago)
- Topics: fastify, fastify-plugin
- Language: JavaScript
- Size: 102 KB
- Stars: 24
- Watchers: 16
- Forks: 8
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- awesome-fastify - `fastify-accepts-serializer`
README
# @fastify/accepts-serializer
![CI](https://github.com/fastify/fastify-accepts-serializer/workflows/CI/badge.svg)
[![npm version](https://img.shields.io/npm/v/@fastify/accepts-serializer)](https://www.npmjs.com/package/@fastify/accepts-serializer)
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://standardjs.com/)Serialize according to the `Accept` header. Supports Fastify versions `^4.0.0`
## Install
```sh
npm i @fastify/accepts-serializer
```## Usage
```jsconst 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).