fastify / fastify Goto Github PK
View Code? Open in Web Editor NEWFast and low overhead web framework, for Node.js
Home Page: https://www.fastify.dev
License: Other
Fast and low overhead web framework, for Node.js
Home Page: https://www.fastify.dev
License: Other
Why isn't this been implemented? Are there any catches that I might have been missed out?
fastify.get('*', handler)
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.
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?
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.
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 :
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?
we need a generic support for content types
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?
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
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
})
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:
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.
as titled
as titled π―ββοΈ π―
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'
.
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:
new request => middlware => onRequest => router => validation => Request/Reply => 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?
I looked through the docs and the tests but don't see what you're using to execute the X/rps.
Input validation via json-schema using ajv for perf reasons.
Ajv bench:
This would be a really nice one, I'm not even sure if we want this in the first place. This is a placeholder issue to discuss.
Something like http://npm.im/vision, that provides plugin-specific views.
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?
It should not be needed
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.
Before starting to implement the template (#30) and authentication (#10) support we must figure out how expose some APIs to build plugins for fastify without changing the core.
This issue is a placeholder for discussion.
cc @mcollina @davidmarkclements @lucamaraschi @marcbachmann
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?
We need to figure our how authentication would work in fastify.
pino of course!
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:
we should provide some support for etag, last-modified and the others.
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
?
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).
We should be able to call reply(null, stream)
.
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 πͺ
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
There is a collection of frequently asked questions and of course you may always ask my humans.
Your Greenkeeper Bot π΄
Is there a way for me to stream a response via fastify (essentially access res.write
)?
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
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.
We should probably do a fastify organization :)
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 πͺ
The new version differs by 4 commits.
0498afe
Bumped v1.3.1
f58fba5
Merge pull request #18 from delvedor/cache-find
2133d0b
fix deopt
7253d83
Call find only one time
See the full diff
There is a collection of frequently asked questions and of course you may always ask my humans.
Your Greenkeeper Bot π΄
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
.
'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)
})
We can base ourselves on https://github.com/yoshuawuyts/bankai, or we can get inspired and write our own thing.
After moving the repo to the organization both travis and coveralls not behave as before, probably they need to be reconfigured.
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' })
})
})
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.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.