diff --git a/README.md b/README.md index 781c0c4..69606b2 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,14 @@ fastify.get('/', (req, reply) => { }) ``` +#### `request.is` +The `request` interface is decorated with [`jshttp/type-is`](https://github.com/jshttp/type-is), the API is the same, but you don't need to pass the request object. +```js +fastify.get('/', (req, reply) => { + reply.send(req.is(['html', 'json'])) +}) +``` + #### `assert` Verify if a given condition is true, if not it throws the specified http error.
Very useful if you work with *async* routes. ```js diff --git a/index.js b/index.js index fa2436c..a6e0eb4 100644 --- a/index.js +++ b/index.js @@ -4,6 +4,7 @@ const fp = require('fastify-plugin') // External utilities const forwarded = require('forwarded') const proxyaddr = require('proxy-addr') +const typeis = require('type-is') // Internals Utilities const httpErrors = require('./lib/httpErrors') const assert = require('./lib/assert') @@ -22,6 +23,10 @@ function fastifySensible (fastify, opts, next) { return proxyaddr(this.raw, trust) }) + fastify.decorateRequest('is', function (types) { + return typeis(this.raw, Array.isArray(types) ? types : [types]) + }) + fastify.decorateReply('vary', vary) // TODO: benchmark if this closure causes some performance drop diff --git a/package.json b/package.json index 2601306..0352d14 100644 --- a/package.json +++ b/package.json @@ -32,6 +32,7 @@ "fastify-plugin": "^0.2.2", "forwarded": "^0.1.2", "proxy-addr": "^2.0.3", + "type-is": "^1.6.16", "vary": "^1.1.2" } } diff --git a/test/is.test.js b/test/is.test.js new file mode 100644 index 0000000..11fe06a --- /dev/null +++ b/test/is.test.js @@ -0,0 +1,53 @@ +'use strict' + +const { test } = require('tap') +const Fastify = require('fastify') +const Sensible = require('../index') + +test('request.is API', t => { + t.plan(3) + + const fastify = Fastify() + fastify.register(Sensible) + + fastify.get('/', (req, reply) => { + reply.send(req.is('json')) + }) + + fastify.inject({ + method: 'GET', + url: '/', + payload: { foo: 'bar' } + }, (err, res) => { + t.error(err) + t.strictEqual(res.statusCode, 200) + t.deepEqual( + res.payload, + 'json' + ) + }) +}) + +test('request.is API (with array)', t => { + t.plan(3) + + const fastify = Fastify() + fastify.register(Sensible) + + fastify.get('/', (req, reply) => { + reply.send(req.is(['html', 'json'])) + }) + + fastify.inject({ + method: 'GET', + url: '/', + payload: { foo: 'bar' } + }, (err, res) => { + t.error(err) + t.strictEqual(res.statusCode, 200) + t.deepEqual( + res.payload, + 'json' + ) + }) +})