Launch Week Day 5: Introducing Reachability for PHP.Learn More
Socket
Book a DemoSign in
Socket

fastify-accepts

Package Overview
Dependencies
Maintainers
17
Versions
12
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

fastify-accepts - npm Package Compare versions

Comparing version
2.2.0
to
2.3.0
+4
-59
index.js
'use strict'
const accepts = require('accepts')
const warning = require('process-warning')()
warning.create('FastifyWarning.fastify-accepts', 'FST_MODULE_DEP_fastify-accepts'.toUpperCase(), 'fastify-accepts has been deprecated. Use @fastify/accepts@3.0.0 instead.')
warning.emit('FST_MODULE_DEP_fastify-accepts'.toUpperCase())
const fp = require('fastify-plugin')
const acceptsObjectSymbol = Symbol('acceptsObject')
const methodNames = [
'charset', 'charsets',
'encoding', 'encodings',
'language', 'languages',
'type', 'types'
]
function acceptsMethod () {
if (!this.raw[acceptsObjectSymbol]) {
this.raw[acceptsObjectSymbol] = accepts(this.raw)
}
return this.raw[acceptsObjectSymbol]
}
function replyAcceptMethod () {
if (!this.request[acceptsObjectSymbol]) {
this.request[acceptsObjectSymbol] = accepts(this.request.raw)
}
return this.request[acceptsObjectSymbol]
}
function fastifyAcceptHeader (fastify, options, done) {
const decorateReplyToo = options.decorateReply
fastify.decorateRequest('accepts', acceptsMethod)
methodNames.forEach(methodName => {
fastify.decorateRequest(methodName, function (arr) {
const acceptsObject = this.accepts()
if (arguments.length === 0) return acceptsObject[methodName]()
return acceptsObject[methodName](arr)
})
})
if (decorateReplyToo) {
fastify.decorateReply('requestAccepts', replyAcceptMethod)
methodNames.forEach(methodName => {
const capitalizedMethodName = methodName.replace(/(?:^|\s)\S/g, a => a.toUpperCase())
fastify.decorateReply('request' + capitalizedMethodName, function (arr) {
const acceptsObject = this.requestAccepts()
if (arguments.length === 0) return acceptsObject[methodName]()
return acceptsObject[methodName](arr)
})
})
}
done()
}
module.exports = fp(fastifyAcceptHeader, {
fastify: '3.x',
name: 'fastify-accepts'
})
module.exports = require('fastify-accepts-deprecated')
{
"name": "fastify-accepts",
"version": "2.2.0",
"description": "Add accept parser to fastify",
"version": "2.3.0",
"main": "index.js",
"devDependencies": {
"@types/accepts": "^1.3.5",
"@types/node": "^17.0.0",
"fastify": "^3.0.0-rc.4",
"pre-commit": "^1.2.2",
"request": "^2.88.0",
"snazzy": "^9.0.0",
"standard": "^16.0.0",
"tap": "^16.0.0",
"typescript": "^4.0.2",
"tsd": "^0.19.0"
"license": "MIT",
"repository": {
"url": "git://github.com/fastify/fastify-accepts.git"
},
"engines": {
"node": ">=10"
},
"homepage": "https://github.com/fastify/fastify-accepts",
"dependencies": {
"accepts": "^1.3.5",
"fastify-plugin": "^3.0.0"
},
"scripts": {
"lint": "standard | snazzy",
"test": "npm run lint && npm run unit && npm run typescript",
"test:ci": "npm run lint && tap test.js --coverage-report=lcovonly && npm run typescript",
"typescript": "tsd",
"unit": "tap --100 test.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/fastify/fastify-accepts.git"
},
"author": "allevo",
"license": "MIT",
"bugs": {
"url": "https://github.com/fastify/fastify-accepts/issues"
},
"homepage": "https://github.com/fastify/fastify-accepts#readme"
"process-warning": "^1.0.0",
"fastify-accepts-deprecated": "npm:fastify-accepts@2.2.0"
}
}
# fastify-accepts
![CI](https://github.com/fastify/fastify-accepts/workflows/CI/badge.svg)
[![NPM version](https://img.shields.io/npm/v/fastify-accepts.svg?style=flat)](https://www.npmjs.com/package/fastify-accepts)
[![Known Vulnerabilities](https://snyk.io/test/github/fastify/fastify-accepts/badge.svg)](https://snyk.io/test/github/fastify/fastify-accepts)
[![Coverage Status](https://coveralls.io/repos/github/fastify/fastify-accepts/badge.svg?branch=master)](https://coveralls.io/github/fastify/fastify-accepts?branch=master)
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://standardjs.com/)
Add accepts parser to fastify
## Install
`npm install --save fastify-accepts`
## Usage
```js
const fastify = require('fastify')
const Boom = require('boom')
fastify.register(require('fastify-accepts'))
fastify.post('/', function (req, reply) {
const accept = req.accepts() // Accepts object
switch(accept.type(['json', 'html'])) {
case 'json':
reply.type('application/json').send({hello: 'world'})
break
case 'html':
reply.type('text/html').send('<b>hello, world!</b>')
break
default:
reply.send(Boom.notAcceptable('unacceptable'))
break
}
})
```
See [accepts package](https://www.npmjs.com/package/accepts) for all available APIs.
This plugin adds to `Request` object all `Accepts` object methods.
```js
fastify.post('/', function (req, reply) {
req.charset(['utf-8'])
req.charsets()
req.encoding(['gzip', 'compress'])
req.encodings()
req.language(['es', 'en'])
req.languages()
req.type(['image/png', 'image/tiff'])
req.types()
})
```
## License
Licensed under [MIT](./LICENSE)
`fastify-accepts@2.3.0` has been deprecated. Please use
`@fastify/accepts@3.0.0` instead.
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "monthly"
open-pull-requests-limit: 10
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 10
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 15
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 7
# Issues with these labels will never be considered stale
exemptLabels:
- "discussion"
- "feature request"
- "bug"
- "help wanted"
- "plugin suggestion"
- "good first issue"
# Label to use when marking an issue as stale
staleLabel: stale
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed if no further activity occurs. Thank you
for your contributions.
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: false
name: CI
'on':
push:
paths-ignore:
- docs/**
- '*.md'
pull_request:
paths-ignore:
- docs/**
- '*.md'
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
matrix:
node-version:
- 10
- 12
- 14
- 16
os:
- macOS-latest
- windows-latest
- ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Use Node.js
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
- name: Install Dependencies
run: |
npm install --ignore-scripts
- name: Run Tests
run: |
npm run test:ci
- name: Coveralls Parallel
uses: coverallsapp/github-action@1.1.3
with:
github-token: ${{ secrets.github_token }}
parallel: true
flag-name: run-${{ matrix.node-version }}-${{ matrix.os }}
coverage:
needs: test
runs-on: ubuntu-latest
steps:
- name: Coveralls Finished
uses: coverallsapp/github-action@1.1.3
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
parallel-finished: true
automerge:
needs: test
runs-on: ubuntu-latest
permissions:
pull-requests: write
contents: write
steps:
- uses: fastify/github-action-merge-dependabot@v3
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
name: release
on:
workflow_dispatch:
inputs:
semver:
description: "The semver to use"
required: true
default: "patch"
type: choice
options:
- patch
- minor
- major
tag:
description: "The npm tag"
required: false
default: "latest"
pull_request:
types: [closed]
jobs:
call-reuseable-workflow:
uses: fastify/workflows/.github/workflows/release-package.yml@automated-release
with:
semver: ${{ github.event.inputs.semver }}
tag: ${{ github.event.inputs.tag }}
secrets:
ORG_NPM_TOKEN: ${{ secrets.ORG_NPM_TOKEN }}
ORG_MEMBER_OPTIC_TOKEN: ${{ secrets[format('ORG_OPTIC_TOKEN_{0}', github.actor)] }}

Sorry, the diff of this file is not supported yet

import { Accepts } from "accepts"
import { FastifyPlugin } from "fastify"
declare module "fastify" {
interface FastifyRequest extends Accepts {
accepts(): Accepts
}
interface FastifyReply {
requestAccepts(): Accepts
requestCharset: Accepts["charset"]
requestCharsets: Accepts["charsets"]
requestEncoding: Accepts["encoding"]
requestEncodings: Accepts["charsets"]
requestLanguage: Accepts["language"]
requestLanguages: Accepts["languages"]
requestType: Accepts["type"]
requestTypes: Accepts["types"]
}
}
export interface FastifyAcceptsOptions {
decorateReply: boolean
}
declare const fastifyAccepts: FastifyPlugin<FastifyAcceptsOptions>
export default fastifyAccepts
import fastify from "fastify"
import accepts from "."
const app = fastify()
app.register(accepts)
app.get("/", (request, reply) => {
request.accepts()
request.charset()
request.charsets()
request.encoding()
request.encodings()
request.language()
request.languages()
request.type()
request.types()
request.charset(["aa", "aa"])
request.charsets(["aa", "aa"])
request.encoding(["aa", "aa"])
request.encodings(["aa", "aa"])
request.language(["aa", "aa"])
request.languages(["aa", "aa"])
request.type(["aa", "aa"])
request.types(["aa", "aa"])
request.charset("aa", "aa")
request.charsets("aa", "aa")
request.encoding("aa", "aa")
request.encodings("aa", "aa")
request.language("aa", "aa")
request.languages("aa", "aa")
request.type("aa", "aa")
request.types("aa", "aa")
reply.requestAccepts()
reply.requestCharset()
reply.requestCharsets()
reply.requestEncoding()
reply.requestEncodings()
reply.requestLanguage()
reply.requestLanguages()
reply.requestType()
reply.requestTypes()
reply.requestCharset(["aa", "aa"])
reply.requestCharsets(["aa", "aa"])
reply.requestEncoding(["aa", "aa"])
reply.requestEncodings(["aa", "aa"])
reply.requestLanguage(["aa", "aa"])
reply.requestLanguages(["aa", "aa"])
reply.requestType(["aa", "aa"])
reply.requestTypes(["aa", "aa"])
reply.requestCharset("aa", "aa")
reply.requestCharsets("aa", "aa")
reply.requestEncoding("aa", "aa")
reply.requestEncodings("aa", "aa")
reply.requestLanguage("aa", "aa")
reply.requestLanguages("aa", "aa")
reply.requestType("aa", "aa")
reply.requestTypes("aa", "aa")
reply.send({ hello: "world" })
})
MIT License
Copyright (c) 2017 Fastify
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'use strict'
const test = require('tap').test
const plugin = require('./')
const request = require('request')
const Fastify = require('fastify')
const testCases = [
{
name: 'request - no header',
acceptHeader: '',
url: '/request',
expected: {
types: [],
charsets: ['*'],
param1: 'utf1',
param2: 'utf1',
param3: 'utf1',
param4: 'utf1',
param5: 'utf1'
}
},
{
name: 'request - simple',
acceptHeader: 'text/html',
url: '/request',
expected: {
types: ['text/html'],
charsets: ['*'],
param1: 'utf1',
param2: 'utf1',
param3: 'utf1',
param4: 'utf1',
param5: 'utf1'
}
},
{
name: 'request - complex',
acceptHeader: 'text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8',
url: '/request',
expected: {
types: [
'text/html',
'application/xhtml+xml',
'application/xml',
'*/*'
],
charsets: ['*'],
param1: 'utf1',
param2: 'utf1',
param3: 'utf1',
param4: 'utf1',
param5: 'utf1'
}
},
{
name: 'reply - no header',
acceptHeader: '',
url: '/reply',
expected: {
types: [],
param1: 'utf1'
}
},
{
name: 'reply - simple',
acceptHeader: 'text/html',
url: '/reply',
expected: {
types: ['text/html'],
param1: 'utf1'
}
},
{
name: 'reply - complex',
acceptHeader: 'text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8',
url: '/reply',
expected: {
types: [
'text/html',
'application/xhtml+xml',
'application/xml',
'*/*'
],
param1: 'utf1'
}
}
]
test('accept header', t => {
t.plan(testCases.length)
const fastify = Fastify()
fastify.register(plugin, { decorateReply: true })
t.teardown(fastify.close.bind(fastify))
fastify.get('/request', function (req, reply) {
reply.send({
types: req.types(),
charsets: req.charsets(),
param1: req.charsets(['utf1']),
param2: req.charsets(['utf1', 'utf2']),
param3: req.charsets(['utf1', 'utf2', 'utf3']),
param4: req.charsets(['utf1', 'utf2', 'utf3', 'utf4']),
param5: req.charsets(['utf1', 'utf2', 'utf3', 'utf4', 'utf5'])
})
})
fastify.get('/reply', function (req, reply) {
reply.send({
types: reply.requestTypes(),
param1: reply.requestCharsets(['utf1'])
})
})
fastify.listen(0, function () {
const BASE_URL = `http://localhost:${fastify.server.address().port}`
testCases.forEach(function (testCase) {
t.test(testCase.name, (t) => {
t.plan(2)
request({
url: `${BASE_URL}${testCase.url}`,
headers: {
accept: testCase.acceptHeader
},
json: true
}, (err, response, body) => {
t.ok(!err)
t.strictSame(body, testCase.expected)
})
})
})
})
})
test('no reply decorator', async function (t) {
const fastify = Fastify()
fastify.register(plugin, { decorateReply: false })
await fastify.ready()
const methodNames = [
'Charset', 'Charsets',
'Encoding', 'Encodings',
'Language', 'Languages',
'Type', 'Types'
]
for (const method of methodNames) {
t.equal(fastify.hasReplyDecorator('request' + method, false), false)
}
})