Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

fastify

Package Overview
Dependencies
Maintainers
2
Versions
289
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

fastify - npm Package Compare versions

Comparing version 0.28.2 to 0.29.0

CONTRIBUTING.md

15

docs/Server-Methods.md

@@ -100,1 +100,16 @@ <h1 align="center">Fastify</h1>

Set the schema compiler for all routes [here](https://github.com/fastify/fastify/blob/master/docs/Validation-And-Serialize.md#schema-compiler).
<a name="set-not-found-handler"></a>
#### setNotFoundHandler
`fastify.setNotFoundHandler(handler(request, reply))`: set the 404 handler.
This call is fully encapsulated, so different plugins can set different
not found handlers.
<a name="set-error-handler"></a>
#### setErrorHandler
`fastify.setErrorHandler(handler(error, reply))`: set a function that
will be called whenever an error happens. The handler is fully
encapsulated, so different plugins can set different
error handlers.

26

docs/Testing.md
<h1 align="center">Fastify</h1>
## Testing
Testing is one of the most important part when you are developing an application.
Testing is one of the most important part when you are developing an application.
Fastify does not offer a testing framework out of the box, but we can recommend you an handy and nice way to build your unit testing environment.
The modules you'll need:
- [Tap](https://www.npmjs.com/package/tap): an excellent testing framework, it will give you out of the box a very good assertion library and a lot utilities.
- [Tap](https://www.npmjs.com/package/tap): an excellent testing framework, it will give you out of the box a very good assertion library and a lot utilities.
- [Request](https://www.npmjs.com/package/request): a complete library to perform request of any kind.

@@ -96,7 +96,7 @@ - [Minimist](https://www.npmjs.com/package/minimist): a CLI parser, that you will use to run server from the command line.

### Testing with http injection
Fastify supports fake http injection thanks to [shot](https://github.com/hapijs/shot).
Fastify supports fake http injection thanks to [shot](https://github.com/hapijs/shot).
To support this method, you should list `shot` library in your package as dev dependency using
```
npm install shot --save-dev
```
npm install shot@3 --save-dev
```
You just need to use the api `inject`:

@@ -113,2 +113,18 @@ ```js

```
or in the promisified version
```js
const injectOption = {
method: String,
url: String,
payload: Object,
headers: Object
}
fastify.inject(injectOption)
.then(response => {
// your tests
})
```
Example:

@@ -115,0 +131,0 @@ ```js

@@ -139,2 +139,8 @@ 'use strict'

var fourOhFour = FindMyWay({ defaultRoute: fourOhFourFallBack })
fastify.setNotFoundHandler = setNotFoundHandler
setNotFoundHandler.call(fastify)
fastify.setErrorHandler = setErrorHandler
return fastify

@@ -144,4 +150,6 @@

req.id = genReqId()
req.log = res.log = logger.child({ req: req })
req.log = res.log = logger.child({ reqId: req.id })
req.log.info({ req }, 'incoming request')
res._startTime = now()

@@ -262,2 +270,6 @@ res._context = null

if (opts.prefix) {
instance._404Store = null
}
for (var i = 0; i < middlewares.length; i++) {

@@ -340,2 +352,3 @@ instance.use.apply(instance, middlewares[i])

middie: self._middie,
errorHander: self._errorHandler,
schemaCompiler: options.schemaCompiler

@@ -385,2 +398,3 @@ })

config,
opts.errorHander || _fastify._errorHandler,
opts.middie || _fastify._middie

@@ -429,3 +443,3 @@ )

function Store (schema, handler, Reply, Request, contentTypeParser, onRequest, preHandler, onResponse, config, middie) {
function Store (schema, handler, Reply, Request, contentTypeParser, onRequest, preHandler, onResponse, config, errorHandler, middie) {
this.schema = schema

@@ -440,2 +454,3 @@ this.handler = handler

this.config = config
this.errorHandler = errorHandler
this._middie = middie

@@ -477,13 +492,15 @@ }

function inject (opts, cb) {
if (!shot) throw new Error('"shot" library is not installed: "npm install shot --save-dev"')
if (!shot) throw new Error('"shot" library is not installed: "npm install shot@3 --save-dev"')
if (started) {
shot.inject(this, opts, cb)
const waitingForReadyEvent = started
? Promise.resolve()
: new Promise((resolve, reject) => this.ready(err => (err ? reject : resolve)(err)))
const injectPromise = waitingForReadyEvent
.then(() => new Promise(resolve => shot.inject(this, opts, resolve)))
if (cb) {
injectPromise.then(cb, cb)
return
}
this.ready(err => {
if (err) throw err
shot.inject(this, opts, cb)
})
return injectPromise
}

@@ -529,3 +546,17 @@

function defaultRoute (req, res, params) {
function defaultRoute (req, res) {
fourOhFour.lookup(req, res)
}
function basic404 (req, reply) {
reply.code(404).send(new Error('Not found'))
}
function fourOhFourFallBack (req, res) {
// if this happen, we have a very bad bug
// we might want to do some hard debugging
// here, let's print out as much info as
// we can
req.log.warn('the default handler for 404 did not catch this, this is likely a fastify bug, please report it')
req.log.warn(fourOhFour.prettyPrint())
const reply = new Reply(req, res, null)

@@ -535,2 +566,55 @@ reply.code(404).send(new Error('Not found'))

function setNotFoundHandler (opts, handler) {
this.after(() => {
_setNotFoundHandler.call(this, opts, handler)
})
}
function _setNotFoundHandler (opts, handler) {
if (typeof opts === 'function') {
handler = opts
opts = undefined
}
opts = opts || {}
handler = handler || basic404
if (!this._404Store) {
const store = new Store(
opts.schema,
handler,
this._Reply,
this._Request,
opts.contentTypeParser || this._contentTypeParser,
this._hooks.onRequest,
[],
this._hooks.onResponse,
opts.config || {},
this._errorHandler,
this._middie
)
this._404Store = store
var prefix = this._RoutePrefix.prefix
var star = '*'
// TODO this would need to be refactored once
// https://github.com/delvedor/find-my-way/issues/28
// is solved
if (prefix && prefix[prefix.length - 1] !== '/') {
star = '/*'
} else {
fourOhFour.all(prefix + '/', startHooks, store)
fourOhFour.all(prefix + '/*', startHooks, store)
}
fourOhFour.all(prefix + star, startHooks, store)
fourOhFour.all(prefix, startHooks, store)
} else {
this._404Store.handler = handler
this._404Store.contentTypeParser = opts.contentTypeParser || this._contentTypeParser
this._404Store.config = opts.config || {}
}
}
function setSchemaCompiler (schemaCompiler) {

@@ -540,4 +624,9 @@ this._schemaCompiler = schemaCompiler

}
function setErrorHandler (func) {
this._errorHandler = func
return this
}
}
module.exports = build

48

lib/reply.js

@@ -6,3 +6,2 @@ /* eslint-disable no-useless-return */

const pump = require('pump')
const xtend = require('xtend')
const validation = require('./validation')

@@ -20,2 +19,3 @@ const serialize = validation.serialize

this._serializer = null
this._errored = false
}

@@ -60,17 +60,3 @@

if (payload instanceof Error) {
if (!this.res.statusCode || this.res.statusCode < 400) {
this.res.statusCode = 500
}
this._req.log.error({ res: this.res, err: payload }, payload.message)
this.res.setHeader('Content-Type', 'application/json')
setImmediate(
wrapReplyEnd,
this,
stringify(xtend({
error: statusCodes[this.res.statusCode + ''],
message: payload.message,
statusCode: this.res.statusCode
}, this._extendServerError && this._extendServerError(payload)))
)
handleError(this, payload)
return

@@ -175,2 +161,32 @@ }

function handleError (reply, err) {
if (!reply.res.statusCode || reply.res.statusCode < 400) {
reply.res.statusCode = 500
}
reply._req.log.error({ res: reply.res, err }, err.message)
const store = reply.store
const errorHandler = store && store.errorHandler
if (errorHandler && !reply._errored) {
reply.sent = false
reply._errored = true
errorHandler(err, reply)
return
}
reply.res.setHeader('Content-Type', 'application/json')
setImmediate(
wrapReplyEnd,
reply,
stringify(Object.assign({
error: statusCodes[reply.res.statusCode + ''],
message: err.message,
statusCode: reply.res.statusCode
}, reply._extendServerError && reply._extendServerError(err)))
)
return
}
function buildReply (R) {

@@ -177,0 +193,0 @@ function _Reply (req, res, store) {

{
"name": "fastify",
"version": "0.28.2",
"version": "0.29.0",
"description": "Fast and low overhead web framework, for Node.js",

@@ -36,2 +36,19 @@ "main": "fastify.js",

"url": "http://delved.org"
},
{
"name": "Tommaso Allevi",
"email": "tomallevi@gmail.com"
},
{
"name": "James Sumners",
"url": "https://james.sumners.info"
},
{
"name": "Evan Shortiss",
"email": "evanshortiss@gmail.com"
},
{
"name": "Dustin Deus",
"url": "http://starptech.de",
"email": "deusdustin@gmail.com"
}

@@ -62,8 +79,9 @@ ],

"ienoopen": "^1.0.0",
"joi": "^11.0.3",
"joi": "^11.1.1",
"pre-commit": "^1.2.2",
"request": "^2.82.0",
"serve-static": "^1.12.5",
"shot": "^3.4.2",
"snazzy": "^7.0.0",
"split2": "^2.1.1",
"split2": "^2.2.0",
"standard": "^10.0.2",

@@ -76,3 +94,3 @@ "tap": "^10.7.0",

"dependencies": {
"@types/node": "~8.0.27",
"@types/node": "^8.0.30",
"@types/pino": "~4.7.0",

@@ -82,3 +100,3 @@ "ajv": "^5.2.2",

"fast-json-stringify": "^0.13.1",
"fastify-cli": "^0.6.1",
"fastify-cli": "^0.7.0",
"fastseries": "^1.7.2",

@@ -89,5 +107,4 @@ "find-my-way": "^1.5.0",

"pino": "^4.7.2",
"pump": "^1.0.2",
"xtend": "^4.0.1"
"pump": "^1.0.2"
}
}

@@ -97,3 +97,3 @@ <div align="center">

- [`fastify-accepts-serializer`](https://github.com/fastify/fastify-accepts-serializer) to serialize to output according to `Accept` header
- [`fastify-apollo`](https://github.com/coopnd/fastify-apollo) Run an [Apollo Server](https://github.com/apollographql/apollo-server) with Fastify.
- [`fastify-apollo`](https://github.com/coopnd/fastify-apollo) Run an [Apollo Server](https://github.com/apollographql/apollo-server) with Fastify. (GraphQL)
- [`fastify-auth`](https://github.com/fastify/fastify-auth) Run multiple auth functions in Fastify

@@ -104,5 +104,6 @@ - [`fastify-bearer-auth`](https://github.com/fastify/fastify-bearer-auth)

- [`fastify-env`](https://github.com/fastify/fastify-env) Load and check configuration
- [`fastify-formbody`](https://github.com/fastify/fastify-formbody)
Plugin to parse x-www-form-urlencoded bodies
- [`fastify-formbody`](https://github.com/fastify/fastify-formbody) Plugin to parse x-www-form-urlencoded bodies
- [`fastify-graceful-shutdown`](https://github.com/hemerajs/fastify-graceful-shutdown) Shutdown Fastify graceful asynchronously
- [`fastify-helmet`](https://github.com/fastify/fastify-helmet) Important security headers for Fastify
- [`fastify-hemera`](https://github.com/hemerajs/fastify-hemera) Fastify Hemera plugin, for writing reliable & fault-tolerant microservices with [nats.io](https://nats.io/)
- [`fastify-jwt`](https://github.com/fastify/fastify-jwt) JWT utils for Fastify, internally uses [jsonwebtoken](https://github.com/auth0/node-jsonwebtoken)

@@ -118,2 +119,3 @@ - [`fastify-leveldb`](https://github.com/fastify/fastify-leveldb) Plugin to share a common LevelDB connection across Fastify.

Fastify Redis connection plugin, with this you can share the same Redis connection in every part of your server.
- [`fastify-register-timeout`](https://github.com/fastify/fastify-register-timeout) Register plugin with a timeout
- [`fastify-sse`](https://github.com/lolo32/fastify-sse) to provide Server-Sent Events with `reply.sse( … )` to Fastify

@@ -131,19 +133,18 @@ - [`fastify-swagger`](https://github.com/fastify/fastify-swagger)

### Matteo Collina
_Fastify_ is the result of the work of a great community.
Team members are listed in alphabetical order.
<https://github.com/mcollina>
### Lead Maintainers
<https://www.npmjs.com/~matteo.collina>
* [__Matteo Collina__](https://github.com/mcollina), <https://twitter.com/matteocollina>, <https://www.npmjs.com/~matteo.collina>
* [__Tomas Della Vedova__](https://github.com/delvedor), <https://twitter.com/delvedor>, <https://www.npmjs.com/~delvedor>
<https://twitter.com/matteocollina>
### Collaborators
* [__Dustin Deus__](https://github.com/StarpTech), <https://twitter.com/dustindeus>, <https://www.npmjs.com/~starptech>
* [__Evan Shortiss__](https://github.com/evanshortiss), <https://twitter.com/evanshortiss>, <https://www.npmjs.com/~evanshortiss>
* [__James Sumners__](https://github.com/jsumners), <https://twitter.com/jsumners79>, <https://www.npmjs.com/~jsumners>
* [__Luciano Mammino__](https://github.com/lmammino), <https://twitter.com/loige>, <https://www.npmjs.com/~lmammino>
* [__Tommaso Allevi__](https://github.com/allevo), <https://twitter.com/allevitommaso>, <https://www.npmjs.com/~allevo>
### Tomas Della Vedova
<https://github.com/delvedor>
<https://www.npmjs.com/~delvedor>
<https://twitter.com/delvedor>
## Acknowledgements

@@ -150,0 +151,0 @@

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc