Coder Social home page Coder Social logo

fastify / fastify Goto Github PK

View Code? Open in Web Editor NEW
31.5K 298.0 2.2K 8.17 MB

Fast and low overhead web framework, for Node.js

Home Page: https://www.fastify.dev

License: Other

JavaScript 90.94% TypeScript 9.00% Shell 0.05%
webframework performance speed nodejs

fastify's Issues

Error responses are not stringified correctly

Use case:

fastify.addHook('preHandler', (req, reply, next) => {
  if (someCondition) {
    return next(new Error('some error'))
  }
}

If the error case is triggered, the client will receive {}, because JSON.stringify does not stringify the error properties.
This can be easily fixed by doing the following:

JSON.stringify(new Error('some error', ['message', 'arguments', 'type', 'name']))
// => "{"message":"some error","name":"Error"}"

The reply implementation of the error handling uses fast-json-stringify that does not support replacer functions, so we can make a PR to fast-json-stringify or move to JSON.stringify for the errors.

Error code shorthand in hooks handling does not work correctly

Use case:

// first hook
fastify.addHook('preHanlder', (req, reply, done) => {
  done()
})
// second hook
fastify.addHook('preHanlder', (req, reply, done) => {
  done(new Error('some error'), 400)
})

The expected response must have a statusCode equal to 400, instead we got 500, because of this.
Since the hooks that returns an error is the second, the error status code will be in code[1].

@mcollina suggestions?

Multiple response types

Is there a way to define multiple response types? For example a route response my have a different structure for a success/error response.

I have a route that returns an array of objects on success, but an error object on failure.

body schema minLength not working

Just found that minLength in json schema isn't working as expected.
The required works, but not the minLength, am I missing something ?

my code with node js 7.10.0 :

'use strict';

const fastify = require('fastify')();

fastify.post('/test', {
   body: {
      name: {
         type: 'string',
         minLength: 6,
      },
      required: ['name'],
   }
}, (req, res) => {
   console.log(req.body);
   res.send({hello: 'world'});
});

fastify.listen(3400, (err) => {
   if (err) throw err;
   console.log('listening on port 3400');
});

and the response with postman :

screen shot 2017-05-19 at 10 58 49 pm

Close: Not running error

If you call the close api without an active server, you will get the Error: Not running error.
This is very inconvenient if you are using the inject api in your test.

Example:

const { beforeEach, afterEach, test } = require('tap')
const build = require('./server')

var instance = null

beforeEach(done => {
  build(i => {
    instance = i
    done()
  })
})

afterEach(done => {
  instance.close(err => {
    if (err) throw err
    done() // this will never be called
  })
})

test(...)

Use the close api is very useful if you must close some db connection, but this error is tricky and annoying.
An user-side solution could be:

afterEach(done => {
  instance.close(err => {
    if (err.message !== 'Not running') throw err
    done()
  })
})

Maybe we can directly handle that error in our internals.

fastify.server.close(err => {
  if (err.message === 'Not running') err = null
  cb(err)
})

Thoughts?

Out schema for non 2xx response

Currently the out schema is applied to every response.
Is there a way to set a "global" out schema for all non 2xx request?
Or apply the out schema only to the 2xx response?
Any suggestions?

Serving static files

I haven't found any documentation about serving static files, then @mcollina put me on the right path suggesting to try a middleware for it.

Express serve-static works like a charm to map a folder to /:

fastify.use(serveStatic(`${__dirname}/public`))
> curl http://localhost:8888/index.html
<html>
  <head><title>public/index.html</title></head>
  <body>Hello world!</body>
</html>

but I couldn't find a way to map a path to the public folder.
If I wanted to do the same on Express I would have something on the lines of

app.use('/assets', serveStatic(`${__dirname}/dist`))

It would be a nice addition

Hooks context

If you use decorate to add a new function to Fastify, that function will have Fastify as context, for example:

fastify.decorate('test', function () {
  console.log(this) // this is fastify
})

While if you add a hook the context is undefined. Could be useful bind it by default?

fastify.addHook('onRequest', function (req, reply, next) {
  console.log(this) // undefined
})

Add more benchmarks

The current benchmarks are a bit boring and don't say the full story:

Benchmarks

Hapi: 2200 req/sec
Restify: 6133 req/sec
Express: 8534 req/sec
Koa: 9640 req/sec
Fastify: 21287 req/sec

Some information that people would like to know:

  • Time to first byte
  • Response time
  • Scalability

If you Google "nginx vs express.js benchmark" and similar, there will be quite a few benchmarks/ graphs that would be nice to have.

This is your main selling point. I'd focus on that. Good luck.

README

as titled πŸ‘―β€β™‚οΈ πŸ‘―

Using regex when capturing the parameters

The following route definition works in Express.js, but does not work in Fastify, /cinema-logos/:cinemaId(\\d+)-:cinemaName.svg.

In Fastify, it produces params: { 'cinemaId(\d+)-:cinemaName.svg': '1000146-vue.svg' },, whereas I expect to get cinemaId and cinemaName as separate parameters.

:cinemaId-:cinemaName is not working either, because the matching expression appears to be greedy: 'cinemaId-:cinemaName.svg': '1000146-vue.svg'.

Hooks

Another feature that I think we need to implement are Hooks.

I'm developing in my local copy the onRequest hook to make some experiments and I'm very happy with the result. A decision that I must take at the moment is: where call the onRequestHook inside the lifecycle of fastify.

These are the two options:

  1. after the middleware execution but before the routing function:
new request => middlware => onRequest => router => validation => Request/Reply => handler
  1. after the routing function, the validation and the creation of the object Reques and Repy, but before the user's handler.
new request => middlware => router => validation => Request/Reply => onRequest => handler

From the function perspective the difference is:
in the first case the function makes changes on the "vanilla" request and response object from node core, in the second case the function will work on Request and Reply objects from fastify.

But the main difference is that in the first case the change will work for all the routes (for example can change the req.url), while in the second one the user will access the instances of Request/Reply of the specific route. This means that the user could add methods/data to the Request/Reply instances (at runtime!) and use them in the route handler.

Thoughts?

cc: @mcollina @lucamaraschi @davidmarkclements

Expose logger instance?

The configured logger is exposed during requests, but it may be useful to expose it as a property. For example:

const fastify = require('fastify')()
const log = fastify.logger

Thoughts?

querystring validation/parsing

First off, thanks for creating this, I'm very excited to see where this goes, and it has been great to work with thus far.

Question about querystring in the schema, it doesn't appear to be doing anything. I'm hoping you could point out what I'm missing:

Here's an example:

fastify.route({
    "method": "GET",
    "url": "/list",
    "schema": {
      "querystring": {
        "limit": {
          "type": "integer"
        }
      },
      "out": {
        "type": "array",
        "items": {
          "type": "object",
          "properties": {
            "id": {
              "type": "string"
            },
            "count": {
              "type": "integer"
            }
          }
        }
      }
    }
  })

req.query outputs:

Valid query: /list?limit=10
{ limit: '10' } // Limit is a string

Invalid query param: /list?limit=a
{ limit: 'a' } // Invalid limit passed through as string

Extra query params: /list?limit=1&lookatme=true
{ limit: 'a', lookatme: 'true' }

Hopefully you can tell me what I'm doing incorrectly, thanks.

Content type with charset

When using 'Content-Type': 'application/json' some http client append the charset to the header, so the content type becomes 'application/json;charset=utf-8'.
When this happens, Fastify returns a 415, because of our check

if (req.headers['content-type'] && req.headers['content-type'] === 'application/json') {

An easy fix is use .indexOf or .split(;)[0]

if (req.headers['content-type'] && req.headers['content-type'].indexOf('application/json') > -1) {

I ran the benchmarks and there wasn't any sensible changes.
Any other idea to solve this?

cc @mcollina @lucamaraschi

Authentication

We need to figure our how authentication would work in fastify.

query string is not being parsed in middleware handlers

hi,

while implementing the fastify integration for graphql-server i have noticed that in the middleware handler you have to manually parse the query string if you need access to while in the route handler it comes already parsed.

is this the expected behaviour? (in express it comes parsed in middlewares too)

you can see the difference between express and fastify integrations:

Proxy feature

Hi

Just wondering whether you are looking at supporting proxies a bit like H2o2?

Thanks
Simon

Clarification on middleware wildcards

In the docs:

Note that this does not support routes with parameters, (eg: /user/:id/comments) and wildcard is not supported in multiple paths.

Does this mean that /user/* will not match /user/:id/comments?

Renaming fields on response schema

I've browed the schema specs but was not able to find this. I wonder if you have encountered this issue and how you might suggest dealign with it besides just pre parsing my db output which sort of defeats the purpose a bit.

For example if I wished to pull mongo data and expose it through the schema I might want to rename my _id field to id. This seems like a useful option (also along those lines is the restructuring of the response).

Graphics

I've designed this graphic, what do you think?
full logo

An in-range update of ajv is breaking the build 🚨

Version 5.1.6 of ajv just got published.

Branch Build failing 🚨
Dependency ajv
Current Version 5.1.5
Type dependency

This version is covered by your current version range and after updating it in your project the build failed.

ajv is a direct dependency of this project this is very likely breaking your project right now. If other packages depend on you it’s very likely also breaking them.
I recommend you give this issue a very high priority. I’m sure you can resolve this πŸ’ͺ

Status Details
  • ❌ coverage/coveralls Coverage pending from Coveralls.io Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build could not complete due to an error Details

Commits

The new version differs by 8 commits.

  • ff9f93a 5.1.6
  • 0d6ae42 fix: traverse only schema objects, fixes #521
  • daf7d6b docs: using with draft-04
  • 9f0b563 Merge pull request #508 from epoberezkin/greenkeeper/nyc-11.0.2
  • 55727d9 test: remove node v0.12, v5, add v8 to travis test
  • eac5902 chore(package): update nyc to version 11.0.2
  • f1c9f15 Merge pull request #507 from epoberezkin/greenkeeper/chai-4.0.1
  • d74a381 chore(package): update chai to version 4.0.1

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Response stream?

Is there a way for me to stream a response via fastify (essentially access res.write)?

Register - unhandled error

While working at fastify/point-of-view#1 I found that if I pass and error to the next callback of register, even if I handle it, fastify will throw and error.
This because of this specific line of avvio.
Internally we have not a listener for that error event, and node will throw the following error:

< Error: Missing engine
<     at fastifyView (.../point-of-view/index.js:13:10)
<     at Plugin.exec (.../point-of-view/node_modules/avvio/boot.js:191:3)
<     at Boot.loadPlugin (.../point-of-view/node_modules/avvio/boot.js:205:10)
<     at release (.../point-of-view/node_modules/fastq/queue.js:127:16)
<     at Object.resume (.../point-of-view/node_modules/fastq/queue.js:61:7)
<     at _combinedTickCallback (internal/process/next_tick.js:67:7)
<     at process._tickCallback (internal/process/next_tick.js:98:9)
<     at Timeout.Module.runMain [as _onTimeout] (module.js:606:11)
<     at ontimeout (timers.js:365:14)
<     at tryOnTimeout (timers.js:237:5)
< events.js:160
<       throw er; // Unhandled 'error' event
<     

This can be easily fixed with the following line inside Fastify.

app.on('error', () => {})

Now the question is, how do we want to solve this issue?
The faster solution is to update avvio, remove the error emitter and update the noop function is this way:

function noop (err) {
  if (err) throw err
}

But I think that in the scope of avvio as is, that error emitter is useful to catch global errors.
Contrariwise, in Fastify it does not make sense imo, because is counterintuitive for the user.

Thoughts?
cc @mcollina

url wildcard support

Are you guys planning on url wildcard support in the routes ? I'm not sure if it's possible with the current setup . Also, I'm not sure if it should be handled on the frame work or inside wayfarer.

organization

We should probably do a fastify organization :)

An in-range update of find-my-way is breaking the build 🚨

Version 1.3.1 of find-my-way just got published.

Branch Build failing 🚨
Dependency find-my-way
Current Version 1.3.0
Type dependency

This version is covered by your current version range and after updating it in your project the build failed.

find-my-way is a direct dependency of this project this is very likely breaking your project right now. If other packages depend on you it’s very likely also breaking them.
I recommend you give this issue a very high priority. I’m sure you can resolve this πŸ’ͺ

Status Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build failed Details
  • βœ… coverage/coveralls First build on greenkeeper/find-my-way-1.3.1 at 96.4% Details

Release Notes v1.3.1
  • Call find only one time - #18
  • Fix deopt - #18
Commits

The new version differs by 4 commits.

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Confusing payload/body API

const route = {
  method: 'POST',
  path: '/foo',
  handler: (req, reply) => {
    reply.send({bar: req.body.bar})
  },
  schema: {
    payload: {
      type: 'object',
      properties: {
        bar: {type: 'string'}
      }
    }
  }
}

Notice that the validation schema for the POST body is labeled payload, whereas within the handler method it is referenced as body. This mix of terminology is confusing, particularly for someone used to using Hapi. Either the validation config should change "payload" to "body", or the handler should be passed req.payload.

Supplying a logger removes the stream of the logger

'use strict'

const log = require('pino')()
const fastify = require('fastify')({logger: log})

log.info('pino is working')

fastify.get('/', (req, reply) => reply.send({hello: 'world'}))

fastify.listen(8000, (err) => {
  if (err) throw err
  // the next line will fail because `pino-http` removes the stream from `log`
  log.info('server started: http://localhost:%s', fastify.server.address().port)
})

Travis and Coveralls

After moving the repo to the organization both travis and coveralls not behave as before, probably they need to be reconfigured.

Prefix should support / routes

test('Prefix should support /', t => {
  t.plan(1)
  const fastify = Fastify()

  fastify.register(function (fastify, opts, next) {
    fastify.get('/', (req, reply) => {
      reply.send({ hello: 'world' })
    })
    next()
  }, { prefix: '/v1' })

  fastify.inject({
    method: 'GET',
    url: '/v1'
  }, res => {
    t.same(JSON.parse(res.payload), { hello: 'world' })
  })
})

Update benchmarks

Due to using pino-http, we are losing 2k req/s on my laptop.
maybe we can improve pino-http, but we should update our benchmark.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.