status
stringclasses 1
value | repo_name
stringlengths 9
24
| repo_url
stringlengths 28
43
| issue_id
int64 1
104k
| updated_files
stringlengths 8
1.76k
| title
stringlengths 4
369
| body
stringlengths 0
254k
β | issue_url
stringlengths 37
56
| pull_url
stringlengths 37
54
| before_fix_sha
stringlengths 40
40
| after_fix_sha
stringlengths 40
40
| report_datetime
unknown | language
stringclasses 5
values | commit_datetime
unknown |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
closed | fastify/fastify | https://github.com/fastify/fastify | 2,897 | ["docs/Ecosystem.md"] | Add fastify-schema-to-typescript to ecosystem | Hi team,
I've been working on this tool to generate typescript types from a json schema. It allows to have types that match the validation schema.
Would it be possible to add it to the ecosystem? If no would it be possible to have some feedback to make it better
Here's the repo https://github.com/thomasthiebaud/fastify-schema-to-typescript | https://github.com/fastify/fastify/issues/2897 | https://github.com/fastify/fastify/pull/2898 | fefab178bc1cc14cfd5965583500800ff0c61d27 | efa77faeac506c0339c28a6708d42a0876d8e2d5 | "2021-03-05T08:44:00Z" | javascript | "2021-03-05T23:33:17Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,885 | ["docs/ContentTypeParser.md", "lib/contentTypeParser.js", "lib/errors.js", "test/content-parser.test.js", "test/custom-parser.test.js", "types/content-type-parser.d.ts"] | Support RegExp for the addContentTypeParser API | <!--
Before you submit an issue we recommend you visit [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify.
**Please read this entire template before posting any issue. If you ignore these instructions
and post an issue here that does not follow the instructions, your issue might be closed,
locked, and assigned the `missing discussion` label.**
-->
## π Feature Proposal
Support `RegExp` for the `addContentTypeParser` API.
## Motivation
Currently, you need to add a new content type parser for each new content type you use. So you have to add 2 parsers if you use the content types `application/vnd.user+json` and `application/vnd.book+json`, even though both are valid JSON objects and could use the same content type parser. This could be possible if the `addContentTypeParser` API supported `RegExp` in addition to string values.
## Example
```javascript
fastify.addContentTypeParser(/s*\+json$/, { parseAs: "string" }, function (req, body, done) {
try {
var json = JSON.parse(body)
done(null, json)
} catch (err) {
err.statusCode = 400
done(err, undefined)
}
})
```
| https://github.com/fastify/fastify/issues/2885 | https://github.com/fastify/fastify/pull/2890 | 0b6ca3afaa4687ee83412ab010df62b8261a3684 | fefab178bc1cc14cfd5965583500800ff0c61d27 | "2021-02-28T10:37:47Z" | javascript | "2021-03-05T09:19:49Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,852 | ["docs/Reference/Validation-and-Serialization.md", "package.json", "test/schema-feature.test.js"] | Should array support in validation be enabled by default? | ## π Feature Proposal
In #2841 the question came up whether supporting array validation should be enabled by default, and I was asked to open a new issue to discuss the breaking change.
My naive reasoning was:
- In cases that don't use `type: 'array'` in the schema there shouldn't be an impact on either behavior or performance, because nothing gets coerced as array anyway.
- As soon as arrays are involved, users probably would want to have it enabled to make it actually do what is intuitively expected. In particular in query string validation, arrays do not work by default without array coercing as discussed in in #2841.
- Even for body validation where arrays do work already there shouldn't be a performance difference: The validation has to run `Array.isArray` anyway, and no further coercion is required in these cases where the object already is an array.
The question is if this would be a semver-major change. As far as I can see the change would strictly increase the set of inputs that pass validation, i.e., everything that has passed validation before still passes validation, but there is now more input that fits to the schema, because scalars / missing values could be coerced to 1-element or 0-element arrays. In the case of query string validation this is certainly desired, because otherwise passing-in arrays isn't working (easily / by default). In the case of request body validation it is a question of API strictness whether one considers it a breaking change. Looks like a classical problem of semantic versioning: To 90% of the users a scope broadening change like that isn't breaking and may be welcome, but there may be a minority relying on it.
## Motivation
See #2841.
| https://github.com/fastify/fastify/issues/2852 | https://github.com/fastify/fastify/pull/3594 | 38fc063ecd3febeb7e2d93453760ab4cd9147845 | 0033f739d4c8471b55991835f92eee94d7491292 | "2021-02-13T11:12:44Z" | javascript | "2022-01-06T08:16:17Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,842 | ["docs/Errors.md", "fastify.js", "lib/errors.js", "lib/hooks.js", "package.json", "test/hooks.on-ready.test.js", "test/plugin.test.js"] | Improve errors user experience | Fastify has many assertions around in the codebase to make sure that the user didn't misconfigure something, for instance, it checks if a route has been declared twice or if a plugin is not a function.
This is great, we vastly reduce the possibility of weird runtime issues, but for historical reasons the errors we are emitting are everything but user friendly.
We should improve this situation, as it is a big pain point in our user experience.
Example of double route declaration:
```js
'use strict'
const fastify = require('fastify')()
fastify.get('/', () => {})
fastify.get('/', () => {})
fastify.listen(3000, console.log)
```
```
βΆ node index.js
AssertionError [ERR_ASSERTION]: Method 'GET' already declared for route '/'
at Router._insert (.../fst-err/node_modules/find-my-way/index.js:304:9)
at Router._on (.../fst-err/node_modules/find-my-way/index.js:197:8)
at Router.on (.../fst-err/node_modules/find-my-way/index.js:74:8)
at Object.afterRouteAdded (.../fst-err/node_modules/fastify/lib/route.js:253:16)
at .../fst-err/node_modules/fastify/lib/route.js:187:25
at Object._encapsulateThreeParam (.../fst-err/node_modules/avvio/boot.js:545:7)
at Boot.timeoutCall (.../fst-err/node_modules/avvio/boot.js:447:5)
at Boot.callWithCbOrNextTick (.../fst-err/node_modules/avvio/boot.js:428:19)
at Boot._after (.../fst-err/node_modules/avvio/boot.js:273:26)
at Plugin.exec (.../fst-err/node_modules/avvio/plugin.js:131:17) {
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: false,
expected: true,
operator: '=='
}
```
What I would expect instead is:
```
FastifyError: Method 'GET' already declared for route '/'
at fastify.get('/', () => {}) (.../fst-err/index.js:4:9)
```
Which is quite complex, given that our route declaration is asynchronous.
Another example, this time with bad plugin type:
```js
'use strict'
const fastify = require('fastify')()
fastify.register(null)
fastify.listen(3000, console.log)
```
```
βΆ node index.js
.../fst-err/node_modules/avvio/boot.js:200
throw new Error('plugin must be a function or a promise')
^
Error: plugin must be a function or a promise
at assertPlugin (.../fst-err/node_modules/avvio/boot.js:200:11)
at Boot._addPlugin (.../fst-err/node_modules/avvio/boot.js:233:12)
at Boot.use (.../fst-err/node_modules/avvio/boot.js:209:25)
at Object.server.<computed> [as register] (.../fst-err/node_modules/avvio/boot.js:33:14)
at Object.<anonymous> (.../fst-err/index.js:5:9)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
```
As you can see, the error is not being helpful at all. | https://github.com/fastify/fastify/issues/2842 | https://github.com/fastify/fastify/pull/3106 | 71b21bfafc4b074b2e4d42f20b5e60a4a7ada395 | c631bb71b8c180c8ba326e81455836f93b0d08c9 | "2021-02-09T07:08:07Z" | javascript | "2021-06-05T07:28:52Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,836 | ["docs/Server.md"] | Logger option genReqId not considered | ## π Bug Report
The `genReqId` function specified within the standard Pino Logger options object is not considered, when generating identifiers for incoming requests.
## To Reproduce
```js
fastify({
logger: {
genReqId: req => 'whatever string',
},
});
```
This bug was fixed here https://github.com/fastify/fastify/commit/526e3a5fc243984270ab4cf22609c79c5de409ba, but got reintroduced.
## Expected behavior
According to the docs, the logger's `genReqId` function should be applied.
The fix might be to check if the `logger.genReqId` is set.
```js
// Update the options with the fixed values
...
options.logger = logger
options.genReqId = logger.genReqId || genReqId
options.requestIdHeader = requestIdHeader
...
```
## Your Environment
- *node version*: 14.15
- *fastify version*: 3.11.0
- *os*: Mac
| https://github.com/fastify/fastify/issues/2836 | https://github.com/fastify/fastify/pull/2838 | fc33ae97ed2de9d2c9c262f5efb966c84e942547 | 91d87c54efe961496e85053bdb1bebbdffbd29ef | "2021-02-05T10:43:45Z" | javascript | "2021-02-05T17:53:29Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,813 | ["docs/Request.md", "lib/request.js", "test/schema-special-usage.test.js"] | Validation tries to set headers but its not possible | ## π Bug Report
Hi people, while upgrading to v3 I've noticed a strange behavior.
#2426 has changed headers to be a getter, but `validateParam` (https://github.com/fastify/fastify/blob/master/lib/validation.js#L74) does try to assign it if the validation result contains the `value`. This does not come up with ajv because it mutates the original headers if `coerceTypes` is set. Joi returns the modified value that broke my upgrade to v3. I do not know how do other libraries do that. This did not happen on 2.14, what we are currently using.
I see that since #2355 joi is not supported officially, but this still smells like a bug. It is not clear how we should proceed. We can of course consider moving to ajv, but that is a lot more involved than just updating fastify.
## To Reproduce
Steps to reproduce the behavior:
```js
const Joi = require('joi')
const schemaValidator = ({ schema }) => data => schema.validate(data)
const fastify = require('fastify')({ logger: { leve: 'debug' }})
.setValidatorCompiler(schemaValidator)
const options = {
schema: {
headers: Joi.object({
'user-agent': Joi.string().required(),
host: Joi.string().required()
})
}
}
fastify.post('/', options, (request, reply) => {
reply.status(200)
})
fastify.inject({ method: 'POST', url: '/' })
```
This results in the following stack trace:
```
TypeError: Cannot set property headers of #<Request> which has only a getter
at validateParam (/home/ttancos/node_modules/fastify/lib/validation.js:74:44)
at validate (/home/ttancos/node_modules/fastify/lib/validation.js:92:19)
at preValidationCallback (/home/ttancos/node_modules/fastify/lib/handleRequest.js:87:18)
at handler (/home/ttancos/node_modules/fastify/lib/handleRequest.js:70:7)
at handleRequest (/home/ttancos/node_modules/fastify/lib/handleRequest.js:30:9)
at runPreParsing (/home/ttancos/node_modules/fastify/lib/route.js:416:5)
at Object.routeHandler [as handler] (/home/ttancos/node_modules/fastify/lib/route.js:374:7)
at Router.lookup (/home/ttancos/node_modules/find-my-way/index.js:367:14)
at /home/ttancos/node_modules/fastify/fastify.js:401:11
at manageErr (/home/ttancos/node_modules/fastify/fastify.js:438:11)
```
## Expected behavior
Headers contain the validation result.
## Your Environment
- *node version*: 12.19.1
- *fastify version*: 3.10.1
- *os*: ArchLinux | https://github.com/fastify/fastify/issues/2813 | https://github.com/fastify/fastify/pull/2817 | 612ff0beacd7c803114853dd29ec27f3c7c1178d | fb5e1f176500654a97fc27f91a08288a83eb3ebe | "2021-01-23T10:48:58Z" | javascript | "2021-08-09T19:18:53Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,788 | ["lib/route.js", "test/route.test.js"] | Creates incorrect HEAD route when using exposeHeadRoute | <!--
Before you submit an issue we recommend you visit [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify.
**Please read this entire template before posting any issue. If you ignore these instructions
and post an issue here that does not follow the instructions, your issue might be closed,
locked, and assigned the `missing discussion` label.**
-->
## π Bug Report
As discovered in https://github.com/fastify/fastify/pull/2782#discussion_r554836505, when a route is set up with `exposeHeadRoute: true` with `prefix` and `prefixTrailingSlash`, a mysterious `HEAD` route is created.
Needs more investigation.
## To Reproduce
Steps to reproduce the behavior:
```js
fastify.register(function routes (f, opts, next) {
f.route({
method: 'GET',
url: '/',
exposeHeadRoute: true,
prefixTrailingSlash: 'no-slash',
handler: (req, reply) => {
reply.send({ hello: 'world' })
}
})
next()
}, { prefix: '/prefix' })
```
Creates following routes
- `GET /prefix`
- `HEAD /prefix/prefix` (incorrect)
When `prefixTrailingSlash` is set to `"both"`, it creates an **extra** route.
- `GET /prefix`
- `HEAD /prefix/prefix`
- `GET /prefix/`
- `HEAD /prefix`
- `HEAD /prefix/`
## Expected behavior
Should not create extra or incorrect routes.
| https://github.com/fastify/fastify/issues/2788 | https://github.com/fastify/fastify/pull/2790 | 3634c6e01e4049e946da68647a6aaf5847dbccbd | f3d5742f5398e37401d9ea0766d9a37d6f38f08a | "2021-01-12T06:41:47Z" | javascript | "2021-01-25T09:49:45Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,770 | ["lib/reply.js", "test/internals/reply.test.js"] | preSerialization won't be exeecuted in case of a custom serializer. | If you define a custom [reply serializer](https://www.fastify.io/docs/latest/Reply/#serializerfunc), the `preSerialization` won't be executed.
I think this is a leftover of previous implementations and it should considered a bug.
https://github.com/fastify/fastify/blob/834a4e58de86d7996b50a4663fbf2b0fac4686ee/lib/reply.js#L146-L147
To reproduce:
```js
'use strict'
const fastify = require('fastify')()
fastify.addHook('preSerialization', async (req, reply, payload) => {
console.log('preSerialization', payload)
return payload
})
fastify.get('/', (req, reply) => {
reply
.type('application/json')
.serializer(JSON.stringify)
.send({ hello: 'world' })
})
fastify.inject('/', (e, response) => console.log(response.json()))
``` | https://github.com/fastify/fastify/issues/2770 | https://github.com/fastify/fastify/pull/2773 | 886fd348150476ff1303f7ca28d76546c57a3f15 | 9b0c85472e07cc2907591b3df8f9e7e0b1869b7d | "2020-12-31T17:44:09Z" | javascript | "2021-01-05T08:34:35Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,767 | ["lib/route.js", "test/hooks.test.js", "test/route-prefix.test.js", "test/route.test.js"] | Allow onRoute to alter options without side effects |
## π Feature Proposal
The way the `onRoute` hook can be used is to derive some info from the route settings (for swagger for example), or to __mutate the route definition itself__. However in certain cases Fastify creates two routes from the same definition (see https://github.com/fastify/fastify/blob/834a4e58de86d7996b50a4663fbf2b0fac4686ee/lib/route.js#L163-L170).
I propose to update the `onRoute` hook so that:
```js
fastify.addHook('onRoute', function (opts) {
const copy = Object.assign({}, opts)
copy.onRequest = newHook
return copy
})
```
This is to avoid having some custom state like in: https://github.com/fastify/fastify-compress/pull/141.
Note that the actual change is quite simple, as we just need to alter:
https://github.com/fastify/fastify/blob/834a4e58de86d7996b50a4663fbf2b0fac4686ee/lib/route.js#L200-L207.
This change is semver-major and should target the `next` branch. | https://github.com/fastify/fastify/issues/2767 | https://github.com/fastify/fastify/pull/2782 | 9135e8e79a03e02063b1e6b96115ac6abca5ccf0 | 5a6aa29a113704448433b6cc19f6e33032aae77f | "2020-12-30T12:17:27Z" | javascript | "2021-01-13T21:57:42Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,761 | ["lib/request.js", "package.json", "test/internals/request.test.js"] | [FST_LIGHTMYREQUEST_DEP01] When I run my test units | ## π Bug Report
When I run my test units , i get [FST_LIGHTMYREQUEST_DEP01] deprecation warning.
I use jest for testing and request injetcion:
#sample.spec.js
```js
describe('SampleTest', () => {
/** @type {import('awilix').AwilixContainer} */
let container;
afterEach(async () => {
await container.dispose();
});
it('sample-test', async () => {
// resolve awilix containers that I need
const FastifyOpenApi = container.resolve('FastifyOpenApi');
/** @type {import('fastify').FastifyInstance} app */
const app = FastifyOpenApi.getFastify();
container.resolve('AddSchema');
container.resolve('AddTagApp');
const config = container.resolve('config');
const injectReq = await app.inject({
url: `${config.API_PREFIX}/tag`,
method: 'POST',
payload: {
title: 'title',
description: '',
},
});
expect(injectReq.statusCode).toEqual(200);
});
});
```
My tests passed successfully but I got this deprecation warning:
```
(node:64) [FST_LIGHTMYREQUEST_DEP01] FastifyDeprecationLightMyRequest: You are accessing "request.connection", use "request.socket" instead.
```
I want to know why it happened? and what should I do?
## My Environment
- *node version*: 12.18.3
- *fastify version*: >=3.9
- *os*: ubuntu 20.04
- jest: 26
| https://github.com/fastify/fastify/issues/2761 | https://github.com/fastify/fastify/pull/2849 | 7fdef2dcd7d08c2b908402fa6fb5ecc26b762c41 | e5ed15466f26840bc7a71f8f74da54dcce4192e2 | "2020-12-23T15:00:55Z" | javascript | "2021-02-13T09:18:53Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,760 | ["lib/pluginUtils.js", "test/plugin.test.js"] | Report actual plugin requiring decorator | https://github.com/fastify/fastify/blob/c2c5cfca689234864d5a208301dde10cefab9804/lib/pluginUtils.js#L82-L85
The above assertion isn't too helpful. If a plugin asks for the "foo" decorator on the "fastify" object, then it gives a message like the following when that decorator is not found:
> The decorator 'foo' is not present in Fastify
The stack trace ends up looking something like:
```
"error": {
"generatedMessage": false,
"code": "ERR_ASSERTION",
"actual": false,
"expected": true,
"operator": "==",
"name": "AssertionError",
"message": "The decorator 'mysql' is not present in Fastify",
"errorClass": "AssertionError",
"stacktrace": [
{
"file": "node_modules/fastify/lib/pluginUtils.js",
"method": "<anonymous>",
"lineNumber": 79,
"columnNumber": 5
},
{
"file": "node_modules/fastify/lib/pluginUtils.js",
"method": "Object._checkDecorators",
"lineNumber": 78,
"columnNumber": 14
},
{
"file": "node_modules/fastify/lib/pluginUtils.js",
"method": "Object.checkDecorators",
"lineNumber": 70,
"columnNumber": 44
},
{
"file": "node_modules/fastify/lib/pluginUtils.js",
"method": "Object.registerPlugin",
"lineNumber": 97,
"columnNumber": 19
},
{
"file": "node_modules/fastify/fastify.js",
"method": "Boot.override",
"lineNumber": 566,
"columnNumber": 57
},
{
"file": "node_modules/fastify/node_modules/avvio/plugin.js",
"method": "Plugin.exec",
"lineNumber": 64,
"columnNumber": 31
},
{
"file": "node_modules/fastify/node_modules/avvio/plugin.js",
"method": "Boot.loadPlugin",
"lineNumber": 187,
"columnNumber": 10
},
{
"file": "node_modules/fastify/node_modules/avvio/node_modules/fastq/queue.js",
"method": "release",
"lineNumber": 140,
"columnNumber": 16
},
{
"file": "node_modules/fastify/node_modules/avvio/node_modules/fastq/queue.js",
"method": "Object.resume",
"lineNumber": 74,
"columnNumber": 7
},
{
"file": "node_modules/fastify/node_modules/avvio/plugin.js",
"method": "Plugin.finish",
"lineNumber": 166,
"columnNumber": 10
},
{
"file": "node_modules/fastify/node_modules/avvio/plugin.js",
"method": "<anonymous>",
"lineNumber": 188,
"columnNumber": 12
},
{
"file": "node_modules/fastify/node_modules/avvio/plugin.js",
"method": "done",
"lineNumber": 115,
"columnNumber": 5
}
]
}
}
```
Notice that none of this information gives me any hint as to which plugin is causing this error. | https://github.com/fastify/fastify/issues/2760 | https://github.com/fastify/fastify/pull/2778 | 9b0c85472e07cc2907591b3df8f9e7e0b1869b7d | af87e7bae038abffe46ff51a0bbd5b0c797cf495 | "2020-12-23T14:47:22Z" | javascript | "2021-01-06T17:24:55Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,742 | ["docs/Server.md", "fastify.js", "lib/schema-compilers.js", "lib/schema-controller.js", "package.json", "test/schema-serialization.test.js", "test/schema-special-usage.test.js"] | Ajv@7 upgrade plan | Ajv@6 will be discontinued at 28/2/2021, well before we retire Fastify v3. We are at the early stages of Fastify v4 right now, so there might be 6+ months of potentially unsupported validator against security vulnerabilities. However the code in Ajv@6 is really battle tested, so there might be a small chance of that happening.
I see a couple of options.
### Option 1
Quickly release a Fastify v4 with Ajv@7 to minimize the time where Fastify v3 will have an unsupported validator.
### Option 2
Ship Ajv@7 in Fastify@3 even if it has a few breaking changes. We can also decide to do this _only_ if there is a security vulnerability.
### Option 3
Use `peerDependencies` so that Fastify@3 can work with both Ajv@6 and Ajv@7.
### Option 4
Ignore Ajv@7 for Fastify@3 and release Fastify@4 when we are ready.
## Benefits
Ajv has one key feature that is interesting me a lot: a better "standalone mode: https://github.com/ajv-validator/ajv/blob/master/docs/standalone.md. We could potentially support some pre-compiled schemas so that we can speed up our startup time.
See https://github.com/ajv-validator/ajv/releases/tag/v7.0.0 for more details for all the other changes.
----
Feel free to edit this if you see more options for us.
| https://github.com/fastify/fastify/issues/2742 | https://github.com/fastify/fastify/pull/2862 | 5eeab8b1bdacf14cd7ac2b5785cd0908e8f9693e | 5dfec548f890277cfc2b2f4653e4dd3889af2b3c | "2020-12-16T18:28:21Z" | javascript | "2021-05-21T10:58:02Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,736 | ["lib/reqIdGenFactory.js"] | Have default request id generation generate unique id:s | ## π Feature Proposal
Currently request id:s default to an auto-incremented number, but that number is generated locally in each instance, meaning that if one run two or more instances of Fastify, or restarts a single Fastify instance, then the default generated id:s will be duplicated between between two or more requests:
https://github.com/fastify/fastify/blob/453028bbfbb34a240bddb146549d91261deac495/lib/reqIdGenFactory.js#L3-L9
Instead truly unique string id:s should be generated, by eg. using @mcollina's performant [hyperid](https://github.com/mcollina/hyperid) module.
## Motivation
The general expectation of a request id is that it should uniquely identify a request, across instances and across time. The current solution solves neither.
(Minor bonus motivation: Also, the common style of request id:s is that they are quite long unique text strings, whereas Fastify currently is a bit odd in that it generates an actual number rather than a string, possibly giving people a false impression, as Fastify do persist any incoming `x-request-id` header and few of those will likely be a number. If a developer has assumed that a request id is actually always a number, then that could cause some issues as well.)
## Example
If I want to track down all logs that belong to a single request and filter all of those logs using the request id, then the expectation should be that any log point with the request id of that single request is caused by that request β either within the same application logs or in services called by the current instance and where the request id has been forwarded.
Currently, with a restarted fastify instance or an horizontally scaled fastify instance, the logs of multiple different requests all share the same request id, making the request id in such cases much less useful.
## PR
I can help make a PR if there's agreement on this. | https://github.com/fastify/fastify/issues/2736 | https://github.com/fastify/fastify/pull/2848 | 914000d22694eb30a0601c2fccb232e936e2849c | 291afba794a2ecf780162f27e1b460f9a5670198 | "2020-12-13T18:45:17Z" | javascript | "2021-02-23T08:42:52Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,722 | ["test/types/schema.test-d.ts", "types/instance.d.ts", "types/route.d.ts", "types/schema.d.ts"] | Typescript types for `setSerializerCompiler` mismatch | ## π Bug Report
Similar to #2572 the serializer does not like the type signatures it is given even when using the code sample from the readme.
## To Reproduce
Steps to reproduce the behavior:
```js
fastify.setSerializerCompiler(({ schema, method, url, httpStatus }) => {
return data => JSON.stringify(data)
})
```

## Expected behavior
Typescript accepts the types it is given
## Your Environment
- *node version*: 10, 12, 13
- *fastify version*: >=2.0.0
- *os*: Mac, Windows, Linux
- *any other relevant information*
| https://github.com/fastify/fastify/issues/2722 | https://github.com/fastify/fastify/pull/2745 | 6b64483acc1f27202b393dc5a22ab7bb96e2623c | b9d0859b4b36a609eea6fa55a19b3ce73d5057c7 | "2020-12-04T20:45:59Z" | javascript | "2020-12-17T09:41:15Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,711 | ["test/types/instance.test-d.ts", "types/instance.d.ts"] | FastifyInstance interface doesn't expose errorHandler | ## π Bug Report
While documentation states that `FastifyInstance` has a `errorHandler` method:
https://www.fastify.io/docs/latest/Server/#errorhandler
And it is indeed implemented that way, but when trying to implement in TypeScript with strict compilation it fails as `FastifyInstance` doesn't expose this method:
https://github.com/fastify/fastify/blob/de94d314e940fba2c7021b0e180445a814d4d068/types/instance.d.ts
## To Reproduce
Steps to reproduce the behavior:
```ts
import { fastify } from 'fastify';
const fastify = fastify();
fastify.get('/testErrorHandler', errorHandler: (error, request, reply) => {
if (error.code === 'SOMETHING_SPECIFIC') {
reply.send({ custom: 'response' });
return;
}
fastify.errorHandler(error, request, response); // <-------- this fails compilation
}, async (_request: FastifyRequest, reply: FastifyReply) => {
reply.status(204).send();
});
```
## Expected behavior
The above should work
## Your Environment
- *node version*: v12.13.0
- *fastify version*: 3.8.0
- *os*: Mac
| https://github.com/fastify/fastify/issues/2711 | https://github.com/fastify/fastify/pull/2712 | db39fa74c0d9d5ead9371e414f533f33c2bfd5b5 | 61c8a7bc3c91907e97813b631d35ae1f250b40e2 | "2020-11-26T13:34:10Z" | javascript | "2020-11-28T10:17:49Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,707 | ["lib/hooks.js", "test/hooks-async.test.js"] | schema validation error on an async response does not trigger the error handler | <!--
Before you submit an issue we recommend you visit [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify.
**Please read this entire template before posting any issue. If you ignore these instructions
and post an issue here that does not follow the instructions, your issue might be closed,
locked, and assigned the `missing discussion` label.**
-->
## π Bug Report
When using response schema validation on a route with an async handler errors are not caught by the error handler set using `setErrorHandler`, unlike params schema validation.
### Update
This happens only when an async `preSerialization` handler is also present.
## To Reproduce
Let's take a simple working example:
```js
fastify.addHook("preSerialization", async (request, reply, payload) => payload);
fastify.setErrorHandler((error, request, reply) => {
reply
.status(error.statusCode || 500)
.send(error instanceof Error ? { message: error.message, error: error.name } : error);
});
fastify.get(
'/:id',
{
schema: {
params: {
type: 'object',
required: ['id'],
properties: { id: { type: 'string' } },
},
response: {
200: {
type: 'object',
required: ['id'],
properties: { id: { type: 'string' } },
},
},
},
},
async ({ params: { id } }) => ({ id })
);
```
Now what happens if we mess it up?
1. let's replace the route param from `/:id` to `/:blah`
2. let's replace the response from `({ id })` to `({ blah: id })`
This is what produced from both changes:
1. returns the following response, as expected:
```json
{"message":"params should have required property 'id'","error":"Error"}
```
2. returns nothing and doesn't end the request, prints on the server side:
```
(node:1589948) UnhandledPromiseRejectionWarning: Error: "id" is required!
at Object.$main (eval at build (/home/imoses/workspace/application/node_modules/fast-json-stringify/index.js:158:20), <anonymous>:135:15)
at serialize (/home/imoses/workspace/application/node_modules/fastify/lib/validation.js:116:41)
at preserializeHookEnd (/home/imoses/workspace/application/node_modules/fastify/lib/reply.js:349:15)
at next (/home/imoses/workspace/application/node_modules/fastify/lib/hooks.js:198:7)
at handleResolve (/home/imoses/workspace/application/node_modules/fastify/lib/hooks.js:209:5)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:1589948) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1589948) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
```
## Expected behavior
I expect a validation error on the response schema to be caught and handled by the error handler and not crash the request.
## Your Environment
- *node version*: 14
- *fastify version*: =3.8.0
- *os*: Linux
| https://github.com/fastify/fastify/issues/2707 | https://github.com/fastify/fastify/pull/2713 | 273a76f8a6963cd0f633e7e87f5e053a176e0e66 | db39fa74c0d9d5ead9371e414f533f33c2bfd5b5 | "2020-11-25T13:47:59Z" | javascript | "2020-11-27T14:05:25Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,692 | ["lib/hooks.js", "lib/route.js", "test/hooks.test.js", "test/internals/hookRunner.test.js"] | Errors in `onSend` makes fastify not respond | <!--
Before you submit an issue we recommend you visit [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify.
**Please read this entire template before posting any issue. If you ignore these instructions
and post an issue here that does not follow the instructions, your issue might be closed,
locked, and assigned the `missing discussion` label.**
-->
## π Bug Report
If an `onSend` handler (hook?) throws, the error does not bubble up to the application and the response never finishes.
## To Reproduce
Steps to reproduce the behavior:
```js
const fastify = require('fastify')();
fastify.route({
path: '/hello',
handler(_, reply) {
reply.code(200).send();
},
method: 'GET',
onSend() {
throw new Error('boom');
},
});
fastify.listen(3000);
```
## Expected behavior
It should return a 500 error. Changing `onSend` to
```js
onSend(_, __, ___, done) {
done(new Error('boom'));
},
```
fixes the error. I think those 2 approaches should behave the same.
## Your Environment
- *node version*: 14.15.1
- *fastify version*: 3.8.0
- *os*: macOS
- *any other relevant information* | https://github.com/fastify/fastify/issues/2692 | https://github.com/fastify/fastify/pull/2695 | d7d8c2787698a2e03d9ed02af03027f23d8d3a83 | 088a07c2b26deb93d8d4cd64601bae3e09799b66 | "2020-11-17T09:55:04Z" | javascript | "2020-12-16T08:12:45Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,687 | ["docs/Reply.md", "lib/reply.js", "lib/route.js", "lib/symbols.js", "lib/validation.js", "package.json", "test/hooks.test.js", "test/schema-serialization.test.js"] | Custom error properties via schemas | ## π Feature Proposal
Right now setting the schema response of errors doesn't enhance the default error handler.
```js
const Fastify = require('fastify')
const statusCodes = require('http').STATUS_CODES
async function run () {
const app = Fastify()
app.get('/async-throw', {
schema: {
response: {
'5xx': {
type: 'object',
properties: {
statusCode: { type: 'number' },
code: { type: 'string' },
error: { type: 'string' },
lang: { type: 'string' },
message: { type: 'string' }
}
}
}
}
}, async () => {
const e = new Error('async-throw')
e.code = 'this is a code'
e.lang = 'this is a custom field' // this will be ignored
throw e
})
let res
res = await app.inject('/async-throw')
console.log(res.payload)
// print:
// {"statusCode":500,"code":"this is a code","error":"Internal Server Error","message":"async-throw"}
}
run()
```
## Motivation
The user may customize the default error handler properties just defining the output schema.
This will:
- improve the benefit of using schemas
- spread the pattern to throws `Error` and not object ( #2134 )
- easier way to add custom param to an error object on custom routes
## Example
The user will be able to let the script above works out of the box without the need to customize the error handler like this
```js
app.setErrorHandler(function (error, request, reply) {
const statusCode = reply.statusCode
reply.send({
error: statusCodes[statusCode + ''],
code: error.code,
lang: error.lang,
message: error.message || '',
statusCode: statusCode
})
})
```
| https://github.com/fastify/fastify/issues/2687 | https://github.com/fastify/fastify/pull/2691 | 61c8a7bc3c91907e97813b631d35ae1f250b40e2 | 43ea177527d535cc17ed168dd479e07cc61db19d | "2020-11-14T18:49:14Z" | javascript | "2020-11-29T10:31:23Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,653 | ["lib/wrapThenable.js", "test/async-await.test.js"] | reply.sent is false in setErrorHandler | <!--
Before you submit an issue we recommend you visit [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify.
**Please read this entire template before posting any issue. If you ignore these instructions
and post an issue here that does not follow the instructions, your issue might be closed,
locked, and assigned the `missing discussion` label.**
-->
## π Bug Report
reply.sent property is supposed to indicate, if .send() was already used, but it does not work properly in .setEventHandler(). It will be false, even if .send() was used in the route handler. It will only turn true, if .send() was used in .setEventHandler().
## To Reproduce
Steps to reproduce the behavior:
```js
fastify.setErrorHandler((error, request, reply) => {
console.log(reply.sent);
});
fastify.get('/', async (request, reply) => {
reply.send({ test: true });
throw new Error();
});
```
## Expected behavior
I would expect to see "true" printed in my console, but I see "false".
```js
true
```
## Your Environment
- *node version*: 12.19.0
- *fastify version*: >=3.4.1
- *os*: Linux
| https://github.com/fastify/fastify/issues/2653 | https://github.com/fastify/fastify/pull/2774 | 035ca57a4360900bd2fa81ba1d91405e603f1b5f | 5e0e674823642d851fefb73d78fc590325c880b2 | "2020-10-27T12:39:15Z" | javascript | "2021-01-03T21:17:32Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,644 | ["docs/Request.md", "docs/Server.md"] | Support case insensitive query parameters | ## π Feature Proposal
Could it be possible to support an optional case insentive option for query parameters? Adding the option `caseSensitive: false` does not seems to impact query parameters
## Motivation
For backward compatibilitites you sometime need to support multiple casing
## Example
With that code
```
fastify.get<{ Querystring: { test: string } }>(
"/caseinsensitivequery",
async (request, reply) => {
return { test: request.query.test };
}
);
```
Both tests below should pass
```
let res = await request.get("/caseinsensitivequery?test=yes");
expect(res.body).toEqual({ test: "yes" });
res = await request.get("/caseinsensitivequery?tEsT=yes");
expect(res.body).toEqual({ test: "yes" });
```
| https://github.com/fastify/fastify/issues/2644 | https://github.com/fastify/fastify/pull/3319 | ce6270608be0dd56de629be0df149f94c5df95ba | ad967c2cc878eea3e832503e6a081003d13df110 | "2020-10-23T14:14:08Z" | javascript | "2021-09-19T06:30:24Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,633 | ["docs/Reply.md"] | [Minor] Wrong anchor link in Docs | In der [Docs](https://www.fastify.io/docs/latest/Reply/) for Reply the anchor link for _Redirect_ does not work.
* Link: `#redirectdest`
* actual id: `redirectcode--dest`
I don't know how to fix that. Seems like a problem with the markdown-to-html conversion. | https://github.com/fastify/fastify/issues/2633 | https://github.com/fastify/fastify/pull/2640 | b7e31b387641e9a35cadb6948e758dff14a76b01 | 2e9da06e42c14876547d7e95771aefbc5ebdf878 | "2020-10-20T20:29:00Z" | javascript | "2020-10-22T20:09:39Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,619 | ["docs/Routes.md", "docs/Server.md", "fastify.d.ts", "fastify.js", "lib/headRoute.js", "lib/route.js", "lib/warnings.js", "test/route.test.js", "types/route.d.ts"] | Automatically handle `HEAD` requests in `GET` handler unless explicit `HEAD` handler exists | <!--
Before you submit an issue we recommend you visit [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify.
**Please read this entire template before posting any issue. If you ignore these instructions
and post an issue here that does not follow the instructions, your issue might be closed,
locked, and assigned the `missing discussion` label.**
-->
## π Feature Proposal
Fastify does not automatically handle `HEAD` requests in `GET` handlers, unlike Express.
From [`express`' docs](https://expressjs.com/en/api.html#app.METHOD)
>The `app.get()` function is automatically called for the HTTP `HEAD` method in addition to the `GET` method if `app.head()` was not called for the path before `app.get()`.
I think it makes sense for Fastify to do the same (possibly via some option?).
From [Wikipedia](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods)
>The HEAD method asks for a response identical to that of a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.
As mentioned in https://github.com/fastify/fastify/issues/2061#issuecomment-579848040, `express` just skips sending the body on `HEAD` (via `send`).
I tried to find some issue where this was discussed without finding one. Apologies if this has already been discussed.
## Motivation
Forcing the user to use two handlers (or pass `methods: ['GET', 'HEAD'])` to `fastify.route`) when we almost always have to do the same thing in the handlers (e.g. we need `content-length` header, so the only real difference in the handlers is often if body is sent or not - the user would still have to _construct_ the body) seems unnecessary to me. We also have to manually set the `content-length` header now for the body.
## Example
```js
const express = require('express')();
const fastify = require('fastify')();
express.get('/hello', (_, res) => {
res.send('hi from express');
});
fastify.get('/hello', (_, reply) => {
reply.send('hi from fastify');
});
express.listen(3000);
fastify.listen(3001);
```
```sh-session
$ curl -i http://localhost:3000/hello
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 15
ETag: W/"f-JpU+vo3voFR+FPycQwU/gyiCSag"
Date: Wed, 14 Oct 2020 12:20:54 GMT
Connection: keep-alive
Keep-Alive: timeout=5
hi from express%
$ curl -i http://localhost:3001/hello
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
content-length: 15
Date: Wed, 14 Oct 2020 12:20:56 GMT
Connection: keep-alive
Keep-Alive: timeout=5
hi from fastify%
$ curl -I http://localhost:3000/hello
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 15
ETag: W/"f-JpU+vo3voFR+FPycQwU/gyiCSag"
Date: Wed, 14 Oct 2020 12:20:59 GMT
Connection: keep-alive
Keep-Alive: timeout=5
$ curl -I http://localhost:3001/hello
HTTP/1.1 404 Not Found
content-type: application/json; charset=utf-8
content-length: 78
Date: Wed, 14 Oct 2020 12:21:02 GMT
Connection: keep-alive
Keep-Alive: timeout=5
```
If this change were to be implemented that last request would be correct out of the box. | https://github.com/fastify/fastify/issues/2619 | https://github.com/fastify/fastify/pull/2700 | 27373efa587927f9546fb93489ab2a0455f4b8ca | 834a4e58de86d7996b50a4663fbf2b0fac4686ee | "2020-10-14T12:09:51Z" | javascript | "2020-12-28T18:06:38Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,603 | ["fastify.js", "test/internals/version.test.js", "types/instance.d.ts"] | Plugin registration no longer works with webpack | <!--
Before you submit an issue we recommend you visit [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify.
**Please read this entire template before posting any issue. If you ignore these instructions
and post an issue here that does not follow the instructions, your issue might be closed,
locked, and assigned the `missing discussion` label.**
-->
## π₯ Regression Report
The change from #2549 has caused plugin registration to error when using fastify with webpack.
Previously when checking the version of fastify against the version supported by plugins, the fastify version was being derived from the `fastify/package.json` explicitly in [this block](https://github.com/fastify/fastify-plugin/blob/master/plugin.js#L93-L123).
With the change from #2549, there are two error cases introduced by the file reading logic in [this block](https://github.com/zekth/fastify-1/blob/e8ef66273b722080a4be13996431bea7c0deae6a/fastify.js#L593-L598):
1. A `package.json` for reading is not found because of the project/directory organization in which case `Error: ENOENT: no such file or directory, open '/package.json'` is shown.
2. The fastify version is derived from the `version` in the user project `package.json`. This results in errors of the form `fastify-plugin: {{plugin name}} - expected '>=3.x' fastify version, '{{version from user project package.json}}' is installed`.
## Last working version
Worked up to version: 3.4.1
Stopped working in version: 3.5.0
## To Reproduce
Clone the the *webpack* branch from the project [here](https://github.com/agramian/fastify-examples/tree/webpack).
From a terminal within the project folder execute `npm i; npm run build; npm run start`.
## Expected behavior
Either plugin registration should work as it did before, or the documentation should be updated to recommend how to register plugins going forward when using a bundler like webpack, or as a workaround it should be possible to explicitly define the fastify version when initializing the instance (I will open a PR and reference back here for this).
## Your Environment
- *node version*: v12.18.3
- *fastify version*: >=3.5.1
- *os*: macOS
| https://github.com/fastify/fastify/issues/2603 | https://github.com/fastify/fastify/pull/2605 | 341bbc86c94df5cec49778e9c5657b27cbf59282 | f22cb2f3105d2dfbf4400abe7ade93f48d5d0851 | "2020-10-06T21:41:38Z" | javascript | "2020-10-07T15:34:04Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,572 | ["test/types/schema.test-d.ts", "types/schema.d.ts"] | Typescript types for `setValidatorCompiler` mismatch | ## π Bug Report
Typescript typings no longer work for setting ajv as a schema validator (even when using the code sample from the README).
## To Reproduce
Steps to reproduce the behavior:
```typescript
const ajv = new Ajv({
// the fastify defaults (if needed)
removeAdditional: false,
useDefaults: true, // replace missing properties and items with the values from corresponding default keyword
coerceTypes: true, // change data type of data to match type keyword
allErrors: true, // check for all errors
nullable: true,
})
fastify.setValidatorCompiler(({ schema }) => {
return ajv.compile(schema)
})
```
This yields:
```
src/setupFastify.ts:74:47 - error TS2322: Type 'ValidateFunction' is not assignable to type 'FastifyValidationResult'.
Types of property 'errors' are incompatible.
Type 'ErrorObject[]' is not assignable to type 'FastifySchemaValidationError[]'.
Type 'ErrorObject' is not assignable to type 'FastifySchemaValidationError'.
Property 'message' is optional in type 'ErrorObject' but required in type 'FastifySchemaValidationError'.
74 fastify.setValidatorCompiler(({ schema }) => ajv.compile(schema))
~~~~~~~~~~~~~~~~~~~
node_modules/fastify/types/schema.d.ts:35:37
35 export type FastifySchemaCompiler = (routeSchema: FastifyRouteSchemaDef) => FastifyValidationResult
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The expected type comes from the return type of this signature.
```
It would be nice to get an up to date sample on how to configure fastify with different ajv settings.
## Expected behavior
Typescript compilation succeeds
## Your Environment
- *node version*: 12.13
- *fastify version*: 3.4.1
- *typescript version*: 4.0.3
- *os*: Mac
- *any other relevant information*
| https://github.com/fastify/fastify/issues/2572 | https://github.com/fastify/fastify/pull/2576 | c15e8381b23176bc20c390324941e6abceaf318d | df9fbc183fa05fa1a23781b3f11fbf81f6854033 | "2020-09-22T10:58:48Z" | javascript | "2020-09-23T08:03:41Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,568 | ["docs/Reference/Validation-and-Serialization.md", "lib/handleRequest.js", "lib/validation.js", "test/schema-special-usage.test.js"] | Support for async ajv schemas | <!--
Before you submit an issue we recommend you visit [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify.
**Please read this entire template before posting any issue. If you ignore these instructions
and post an issue here that does not follow the instructions, your issue might be closed,
locked, and assigned the `missing discussion` label.**
-->
## π Feature Proposal
Ajv supports async schema with ability to define your own keywords for validation. But Fastify is not handling async validation properly.
## Motivation
My motivation is to clearly define all request validations in one place (in schema).
## Example
```js
const Ajv = require('ajv');
const fastify = require('fastify');
const app = fastify({});
const ajv = new Ajv({
removeAdditional: true,
useDefaults: true,
coerceTypes: true,
nullable: true,
});
ajv.addKeyword('validator', {
async: true,
errors: false,
validate: (schema, data) => new Promise(
(resolve) => console.log(schema, data) || resolve(false)
),
});
app.setValidatorCompiler(({ schema }) => ajv.compile(schema));
app.get('/', {
schema: {
description: 'Tests if server is working.',
query: {
$async: true,
type: 'object',
properties: {
data: {
type: 'string',
validator: 'custom:validator',
},
},
},
},
handler: (req, res) => console.log(req.query) || res.send('ok'),
});
app.listen(8000, (err) => {
if (err) throw err;
});
```
Send test query
```bash
β― curl http://localhost:8000/?data=test
ok
```
Logs of the query
```bash
β― node testFastify.js
custom:validator asd
[Object: null prototype] { data: 'asd' }
(node:28661) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:28661) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
``` | https://github.com/fastify/fastify/issues/2568 | https://github.com/fastify/fastify/pull/4752 | 4f367eabcdd70be5e969883c44290a83e8d5f18e | a649133ebd60c59b284dcd92834aa20fa5d2a8e1 | "2020-09-21T09:11:35Z" | javascript | "2023-05-26T06:33:00Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,567 | ["lib/route.js", "test/route.test.js"] | Strange behavior with route reusage | <!--
Before you submit an issue we recommend you visit [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify.
**Please read this entire template before posting any issue. If you ignore these instructions
and post an issue here that does not follow the instructions, your issue might be closed,
locked, and assigned the `missing discussion` label.**
-->
## π Bug Report
By reusing the same route inside more than one plugins, I've noticed that the second time the route is registered, its URL is somehow prefixed by the previous plugin. I'm not sure if this behavior is intentional or a bug.
## To Reproduce
```js
const fastify = require('fastify')({ logger: true })
const route = {
method: 'GET',
url: '/',
async handler(request, reply) {
return { hello: 'world' }
},
}
async function v1Plugin(fastify) {
fastify.route(route)
}
async function v2Plugin(fastify) {
fastify.route(route)
}
fastify.register(v1Plugin, { prefix: '/api/v1' })
fastify.register(v2Plugin, { prefix: '/api/v2' })
const start = async () => {
try {
await fastify.listen(3000)
console.log(fastify.printRoutes())
fastify.log.info(`server listening on ${fastify.server.address().port}`)
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()
```
## Expected behavior
I was expecting this output:
```
βββ /
βββ api/v
βββ 1 (GET)
β βββ / (GET)
βββ 2 (GET)
βββ / (GET)
```
I got this instead:
```
βββ /
βββ api/v
βββ 1 (GET)
β βββ / (GET)
βββ 2/api/v1/ (GET)
```
And I can "fix" that by cloning the `route` object and redefining the `url` property:
```js
fastify.route({ ...route, url: '/' })
```
## Your Environment
- *node version*: 12
- *fastify version*: ^3.4.1
- *os*: Linux
| https://github.com/fastify/fastify/issues/2567 | https://github.com/fastify/fastify/pull/2569 | a40de6d26a92b9d4749d610161efef85d2f23157 | c15e8381b23176bc20c390324941e6abceaf318d | "2020-09-21T08:56:35Z" | javascript | "2020-09-22T14:05:29Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,557 | ["docs/TypeScript.md", "fastify.d.ts", "package.json", "test/types/decorate-request-reply.test-d.ts"] | Declaration merging broken for FastifyRequest and FastifyReply | #### What are you trying to achieve or the steps to reproduce?
I've followed the steps for [Creating a TypeScript Fastify Plugin](https://www.fastify.io/docs/latest/TypeScript/#creating-a-typescript-fastify-plugin) exactly (twice), but when I reach step 6 and execute `npm run build` in my terminal I receive four errors from TypeScript (version 4.0.2).
#### What was the result you received?
```
> tsc -p tsconfig.json
error TS2468: Cannot find global value 'Promise'.
index.ts:6:12 - error TS2428: All declarations of 'FastifyRequest' must have identical type parameters.
6 interface FastifyRequest {
~~~~~~~~~~~~~~
index.ts:9:12 - error TS2428: All declarations of 'FastifyReply' must have identical type parameters.
9 interface FastifyReply {
~~~~~~~~~~~~
index.ts:28:60 - error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option.
28 const myPluginAsync: FastifyPluginAsync<MyPluginOptions> = async (fastify, options) => {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Found 4 errors.
```
#### What did you expect?
A successful TypeScript build with no errors.
#### Context
* *node version*: v12.16.2
* *fastify version*: ^3.4.1
* *os*: Linux (Ubuntu 20.04)
| https://github.com/fastify/fastify/issues/2557 | https://github.com/fastify/fastify/pull/2558 | f32061907495eee99f51e93d50aae858f8467aa3 | 29c2af10fa0cc4898a86c66772d6ce4079251ab0 | "2020-09-17T09:04:51Z" | javascript | "2020-09-19T05:25:13Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,602 | ["docs/Errors.md", "fastify.js", "lib/reply.js", "lib/setErrorHeaders.js", "test/reply-error.test.js", "test/route-hooks.test.js"] | Fastify's default error handling can serve unexpected responses | ## π Bug Report
I'm not sure if this is a bug or intended behavior (it is documented to some extent, but it seems like setting your own error handler should disable it), so apologies in advance if this should be a feature request versus a bug report.
Fastify's default error handling checks for properties like `status`, `statusCode`, and `headers` [1] on the error that is thrown and then uses them for preparing part of the response. I was running into an issue when I was testing some errors in a few of my routes. I expected to hit a normal 500, but instead was greeted with a parse error:
```
Parse Error: The response headers can't include "Content-Length" with chunked encoding
```
It turned out some of the APIs I was testing add a lot of additional properties to the errors that are thrown, one of them being the headers of the failed request, which caused Fastify to then set a dozen or so headers from the failed API call on the response to the end user, which made everything blow up from there.
Long story short, any failed API calls that include the request headers will subsequently have a high likelihood of failing in Fastify to the point where an end user won't even get a valid response, they'll get a malformed blob that will be unusable.
While I certainly understand the value in the current implementation, there doesn't appear to be any way to disable this behavior. I believe the only two options I have are:
1. Wrap every single API call in my routes and re-throw errors without the `headers` property that gets added by certain SDKs.
1. Use something like `setErrorHandler` [2] and manually iterate through all the headers and call something like `reply.removeHeader('name')` on each one.
Neither of those options are ideal and both add a bit of unnecessary code (first being far worse than the second). I was hoping I could simply bubble errors to the top and return an error response to the user. Are there any other options I'm missing, or is there any way to disable the logic (based on the code it doesn't appear there is but maybe I'm missing something)?
If this isn't a bug and is intended behavior. Is it possible to move L519 [3] up to the top of the `handleError` function (above L507 at a minimum)? In other words, if a user manually specifies an error handler, Fastify won't modify the response based off any of the error properties? Fastify will only inherit error properties if the user is relying on the default error handling logic?
[1] https://github.com/fastify/fastify/blob/f458cea2d360444fd1a2ca5972e8fca6f2e07d88/lib/reply.js#L507
[2] https://www.fastify.io/docs/latest/Server/#seterrorhandler
[3] https://github.com/fastify/fastify/blob/f458cea2d360444fd1a2ca5972e8fca6f2e07d88/lib/reply.js#L519
## To Reproduce
Steps to reproduce the behavior:
1. Throw an error inside an async route that has a `headers` property.
1. Fastify will automatically set them on the response.
1. Depending on what the headers are, Fastify will try to serve a malformed blob.
## Expected behavior
At the very least, if I'm manually setting my own error handler, I would expect that the reply argument I receive is pristine and hasn't already had status code or headers set. If you're relying on Fastify's default behavior, there's still potentially room for improvement by overriding certain header values if they won't be valid for the error response.
## Workaround
This fixes the issue:
```
app.setErrorHandler(async (err, req, res) => {
Object.keys(res.getHeaders()).forEach((h) => res.removeHeader(h));
// ...
});
```
I know it's a one-liner, but would be awesome if there was a better way. Better yet, if it was possible to define the key from the error that should be used for status, I wouldn't need to manually set an error handler at all. Some SDKs set `error.code === statusCode`, etc.
## Your Environment
- *node version*: 14
- *fastify version*: 3.4.1 (latest)
- *os*: Windows, Linux
| https://github.com/fastify/fastify/issues/2602 | https://github.com/fastify/fastify/pull/2609 | 14f967961623defb907852be9108f710dffa185d | f6ee35587345fac4f4cf9212d139fde97f3ab36e | "2020-09-16T03:02:18Z" | javascript | "2020-11-13T08:56:32Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,543 | ["lib/reply.js", "test/content-length.test.js"] | Invalid content-length in custom ErrorHandler | ## π Bug Report
I add a custom error handler to add some extra data to my api answer (stack, ...).
- I send a request too an elasticsearch server, which reply an answer (an error) with a content-length of 335 bytes.
- In my error handler, I answer with bigger body (more than 335 bytes content-length).
## To Reproduce
If a thrown error have headers.'content-length' properties it is propagated to the fastify answer like #2214 but with an errorHandler.
```js
import fastify from 'fastify';
const server = fastify();
server.get('/', async (request, reply) => {
const error = new Error('MY_ERROR_MESSAGE');
error.headers = {
'content-length': 2,
};
throw error;
});
server.setErrorHandler((error, request, reply) => {
reply.code(500).send({ error: 'longer than 2' });
});
const start = async () => {
await server.listen(3000, '0.0.0.0');
};
start();
```
```
curl -v http://127.0.0.1:3000/
* Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 3000 (#0)
> GET / HTTP/1.1
> Host: 127.0.0.1:3000
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 500 Internal Server Error
< content-length: 2
< content-type: application/json; charset=utf-8
< Date: Tue, 08 Sep 2020 13:33:51 GMT
< Connection: keep-alive
< Keep-Alive: timeout=5
<
* Excess found in a non pipelined read: excess = 23, size = 2, maxdownload = 2, bytecount = 0
* Connection #0 to host 127.0.0.1 left intact
```
## Expected behavior
Answer generated by my error handler should have the right content length.
It has the following side effects :
- if my answer is smaller than 2 bytes : it hangs for 5secs
- if my answer is bigger than 2 bytes : my answer is truncated and my json is not valid.
## Your Environment
- *node version*: 14
- *fastify version*: >=3.3.0
- *os*: Linux
Thx | https://github.com/fastify/fastify/issues/2543 | https://github.com/fastify/fastify/pull/2546 | ee84e873ada86dd8a1ba2e1c862cf1ae4b29a25e | f458cea2d360444fd1a2ca5972e8fca6f2e07d88 | "2020-09-08T13:06:04Z" | javascript | "2020-09-09T15:29:55Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,538 | ["docs/Request.md"] | definition for request hostname is incorrect | ## π Bug Report
in the docs request `hostname` is defined as providing the hostname -- which is very incorrect for [what it actually does](https://github.com/fastify/fastify/blob/f2982a245e55f6c9d0a88837434e8423db6cc0ae/lib/request.js#L74-L81).
what it actually does:
- if request.headers['x-forwared-for'] exists, the value is returned. (i believe this could be an array?)
- host header as-is (so it's returning "host" and not "hostname")
- if no host header exists, [return ":authority"](https://github.com/fastify/fastify/issues/2112)
so, the one thing request.hostname doesn't do is return the hostname. | https://github.com/fastify/fastify/issues/2538 | https://github.com/fastify/fastify/pull/3325 | ad967c2cc878eea3e832503e6a081003d13df110 | c872f0b009bcdd08c5f79b42421f2432075754d2 | "2020-09-04T21:03:21Z" | javascript | "2021-09-20T07:05:55Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,566 | ["docs/ContentTypeParser.md", "docs/Server.md", "fastify.js", "lib/contentTypeParser.js", "test/custom-parser.test.js"] | Import the default (json) content type parser? | #### You have already researched for similiar issues?
It's not uncommon that somebody already opened an issue or in best case it's already fixed but not merged. That's the reason why you should [search](https://github.com/fastify/fastify/issues) at first before submitting a new one.
#### What are you trying to achieve or the steps to reproduce?
I have an external caller that I can't change sending requests with `content-type: text/json` is there any way to use the default built in JSON parser for this? From what I can tell it's not exported so I can't just call `server.addContentTypeParser('text/json', defaultParser)`.
#### What did you expect?
Ability to accept JSON content that other than `application/json` content type set without having to write custom parser.
#### Context
* *node version*: 12
* *fastify version*: 3.2.0
| https://github.com/fastify/fastify/issues/2566 | https://github.com/fastify/fastify/pull/2573 | 4068406b1b63ec895ef62a5e16e12430174bec17 | 4ac15542e730a4ff560e73cbd059e633c05d2106 | "2020-09-04T16:55:39Z" | javascript | "2020-10-10T13:04:24Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,531 | ["fastify.js", "test/404s.test.js"] | Chaining setNotFoundHandler | `setNotFoundHandler` doesn't support chaining calls:
```
fastify
.setNotFoundHandler(function (request, reply) { })
.get('/', schema, function (req, reply) {
reply.send({ hello: 'world' })
})
```
As does `setErrorHandler` and `setValidatorCompiler` etc..
https://github.com/fastify/fastify/blob/21578f56dea6bfd3de1c9a4df497fd535d174221/fastify.js#L499-L503
_Originally posted by @Eomm in https://github.com/fastify/fastify/pull/2467#discussion_r466178333_ | https://github.com/fastify/fastify/issues/2531 | https://github.com/fastify/fastify/pull/2533 | 7369e7e3f0e881afecb5cf8854afb03edc708b83 | 87ed2a4875ed77d4c37039998ab30f88751eb661 | "2020-09-02T19:20:08Z" | javascript | "2020-09-03T12:46:16Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,529 | ["test/types/reply.test-d.ts", "types/reply.d.ts", "types/route.d.ts"] | TypeScript: reply.send validates against argument's type, not route method payload's type | ## π Bug Report
If RouteShorthand method is configured with a specific Reply type, i.e.
```
interface Topics {
items: { id: string }[]
}
fastify.get<{
Reply: Topics
}>('/topics',
{ ... skipped ... },
async (request, reply) => {
reply.send({ items: [123] })
}
)
```
reply.send won't detect a typing error because it uses a type of it's argument, not the type it should be validating against (i.e. Topics).
Using `return` form also doesn't detect the error because it's typed as unknown.
## To Reproduce
Configure Reply and pass incompatible type to reply.send() or return.
## Your Environment
- *node version*: 12
- *fastify version*: >=3.2.1
- *os*: Mac
| https://github.com/fastify/fastify/issues/2529 | https://github.com/fastify/fastify/pull/2530 | ebca8b478afc6584633dc1964ed9e9830ce776c3 | 8ee4a98df4163a04e4beaaa499c809a69231261d | "2020-09-01T05:45:33Z" | javascript | "2020-09-02T14:04:24Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,512 | [".github/workflows/ci.yml"] | Stop running CI on Node 13 | EOL for Node 13 was on 2020-06-01. We probably should stop running CI for it, same as we stopped running it for Node 11. Thoughts? | https://github.com/fastify/fastify/issues/2512 | https://github.com/fastify/fastify/pull/2513 | b9fcf3fae0317a54f4f32c5121d5099d1a4d0ed9 | f71adb1e7cf4ccf189328453ff4551033dae1700 | "2020-08-22T23:34:54Z" | javascript | "2020-08-23T08:16:22Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,500 | ["docs/Guides/Delay-Accepting-Requests.md", "docs/Guides/Index.md"] | Improve developer experience around server listening | ## π Feature Proposal
Document or formalize notifying when the Fastify server is listening for and accepting requests.
## Motivation
I have encountered a need to know when the server is listening for and accepting requests. This is different from our `onReady` hook (which is really `onReadyToListen`). Basic premise is, I have to work with a third party API that requires OAuth 2.0 authorization via the [Authorization Code Grant](https://oauth.net/2/grant-types/authorization-code/) instead of the more desirable [Client Credentials Grant](https://oauth.net/2/grant-types/client-credentials/). As a result, I need to obtain a token upon server start which requires the server to be able to process the callback portion of the ACG flow.
## Example
This is currently achievable by:
```js
async function aPlugin(fastify) {
// Setup some stuff.
fastify.server.on('listening', doSomeThings)
function doSomeThings () {
// Do some things after the server is accepting connections.
// For example, the scenario described in this issue might do:
refreshToken()
.then((token) => {
fastify.acgToken = token // Added by a decorator.
setTimeout(refreshToken, ms('1 hour'))
})
.catch((error) => {
fastify.log.error({ err: error })
process.exit(1)
})
}
}
async function refreshToken() {
await getToken()
}
```
We should either document this or make it more "Fastify-like" with a proper hook.
| https://github.com/fastify/fastify/issues/2500 | https://github.com/fastify/fastify/pull/3837 | bd4914c1b85305e33b3d541bd85f4f288aad910f | c97fa0fc0d73d128ed72ddd7ba101cd0704e6162 | "2020-08-18T13:10:48Z" | javascript | "2022-04-22T13:49:25Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,488 | ["README.md"] | doc: Add discord badge | <!--
Before you submit an issue we recommend you visit [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify.
**Please read this entire template before posting any issue. If you ignore these instructions
and post an issue here that does not follow the instructions, your issue might be closed,
locked, and assigned the `missing discussion` label.**
-->
## π Feature Proposal
To promote the use of discord to make the community grow, the addition of a badge within the others on the README can be a plus. Here is how to setup it : https://shields.io/category/chat
(needs admin permission to allow it on discord side)
## Motivation
Promote the discord server
| https://github.com/fastify/fastify/issues/2488 | https://github.com/fastify/fastify/pull/2489 | 480d985b98c779fd8eb83f54ae0e2e728f1afa27 | 2ad4fde842b4d872c1532030c73efc1685c14eb7 | "2020-08-12T08:36:42Z" | javascript | "2020-08-12T13:38:18Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,455 | ["lib/logger.js", "test/logger.test.js"] | Fastify must not mutate passed in options | <!--
Before you submit an issue we recommend you visit [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify.
**Please read this entire template before posting any issue. If you ignore these instructions
and post an issue here that does not follow the instructions, your issue might be closed,
locked, and assigned the `missing discussion` label.**
-->
## π Bug Report
Fastify mutates passed in options
## To Reproduce
This is mimalistic example to reproduce the issue but the actual issue happens when trying to pass configuration using `config` npm package as options to `fastify` function:
```js
import fastify from 'fastify';
const server = fastify({
logger: Object.defineProperty({}, 'level', { value: 'info' })
});
```
This code throws:
```
Uncaught TypeError: Cannot assign to read only property 'level' of object '#<Object>'
at createLogger (/api/node_modules/fastify/lib/logger.js:85:26)
at fastify (/api/node_modules/fastify/fastify.js:87:33)
```
## Expected behavior
Fastify should not mutate passed in options object
## Your Environment
- *node version*: 12.17.0
- *fastify version*: 3.1.1
- *os*: Linux
| https://github.com/fastify/fastify/issues/2455 | https://github.com/fastify/fastify/pull/2474 | eee6c8dac6959310703699ddee6fb512cab285c3 | e02c80f95e13d2030aab8de03863212cc9a1f4cc | "2020-08-01T18:09:59Z" | javascript | "2020-08-08T13:06:45Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,462 | ["lib/route.js", "lib/schemas.js", "test/schema-feature.test.js", "test/schema-serialization.test.js"] | CORS is breaking Schemas | # π Bug Report
If I define a schema inside a plugin, `fastify-cors` breaks the application when `preflight` is enabled.
## To Reproduce
I created a simple repository showing the problem.
https://github.com/wandersonwhcr/fastify-cors-problem
## Your Environment
- *node version*: 14
- *fastify version*: >=3.1.1
- *os*: Linux
| https://github.com/fastify/fastify/issues/2462 | https://github.com/fastify/fastify/pull/2463 | ff886c7c54d9de1afed4e215d174279f3ad72385 | dbfbb310cd03f46b734f8069e80181dc414942c2 | "2020-07-28T17:38:31Z" | javascript | "2020-08-05T07:12:57Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,439 | ["test/types/hooks.test-d.ts", "types/hooks.d.ts"] | TypeScript: addHook'a 'onSend' callback typings | ## π Bug Report
addHook('onSend') disallows next() without arguments.
## To Reproduce
```
fastify.addHook('onSend', function (_request, reply, payload, next) {
Object.assign(reply.res, { payload })
next() // <--- error
})
```
Error:
```
Expected 1-2 arguments, but got 0.
hooks.d.ts[93, 41]: An argument for 'err' was not provided.
```
## Expected behavior
Code compiles, payload not modified.
## Your Environment
- *node version*: 12
- *fastify version*: >=3.0.3
- *os*: Mac
| https://github.com/fastify/fastify/issues/2439 | https://github.com/fastify/fastify/pull/2485 | 955314d4b51175952f2e62167075cfa349e33434 | c8eb3d47fe0294554e60e1d5ae643612da8f9a2b | "2020-07-27T16:07:44Z" | javascript | "2020-08-12T08:03:49Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,411 | ["lib/errors.js", "lib/server.js", "test/close.test.js"] | Cannot listen on a port after closing the server. Error is misleading. | <!--
Before you submit an issue we recommend you visit [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify.
**Please read this entire template before posting any issue. If you ignore these instructions
and post an issue here that does not follow the instructions, your issue might be closed,
locked, and assigned the `missing discussion` label.**
-->
## π Bug Report
I am trying to temporarily swap out my main fastify server instance with a maintenance server while I handle some background processes.
When I try to swap back to my main server that was previously closed, it throws an error saying `Fastify is already listening`
I'm not sure if this is a bug or not supported since the documentation is unclear.
I have already worked around this by migrating the maintenance logic to the prehandler. I'm just looking for some clarification on the expected behavior or a clearer error message.
## To Reproduce
Here is a minimal example to demonstrate:
```js
const create= require("fastify");
const mainServer = create();
await mainServer.listen(8080, "0.0.0.0");
const maintenanceServer = create();
await mainServer.close();
await maintenanceServer.listen(8080, "0.0.0.0");
await maintenanceServer.close();
await mainServer.listen(8080, "0.0.0.0");
// throws an error with message 'Fastify is already listening'
```
## Expected behavior
Either `mainServer` starts listening on port 8080 or a message saying that the fastify instance has already been closed and cannot be reopened.
## Your Environment
- *node version*: 12.16.1
- *fastify version*: >=2.3.0
- *os*: Windows | https://github.com/fastify/fastify/issues/2411 | https://github.com/fastify/fastify/pull/2415 | d06287a9a612d218d26e3a94b248b5035d5c44cb | e53abd1118a305763d75fe4c3224e42b7166608d | "2020-07-14T23:46:50Z" | javascript | "2020-07-16T15:03:13Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,409 | ["test/types/request.test-d.ts", "types/request.d.ts"] | Add validationErrors property to request object when using attachValidation option |

* *fastify version*: >=3.0.2
* *os*: Linux
| https://github.com/fastify/fastify/issues/2409 | https://github.com/fastify/fastify/pull/2422 | 28881ca8f515789176e37bd6dd5bb1071a40b374 | af880ad3db6bd05468141cd4e136467ab80bfd46 | "2020-07-13T22:11:54Z" | javascript | "2020-07-20T21:37:13Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,403 | ["test/types/dummy-plugin.ts", "test/types/plugin.test-d.ts", "types/register.d.ts"] | ESM-style plugin import doesn't pass TypeScript type check. | ## π Bug Report
## To Reproduce
Pick any Fastify plugin (I'll use `fastify-formbody` for now):
```js
fastify().register(import('fastify-formbody'));
```
TypeScript compiler gives the following error:
```
No overload matches this call.
Overload 1 of 3, '(plugin: FastifyPluginCallback<FastifyPluginOptions>, opts?: FastifyRegisterOptions<FastifyPluginOptions>): FastifyInstance<...> & PromiseLike<...>', gave the following error.
Argument of type 'Promise<typeof import(".../node_modules/fastify-formbody/formbody")>' is not assignable to parameter of type 'FastifyPluginCallback<FastifyPluginOptions>'.
Type 'Promise<typeof import(".../node_modules/fastify-formbody/formbody")>' provides no match for the signature '(instance: FastifyInstance<RawServerBase, IncomingMessage | Http2ServerRequest, ServerResponse | Http2ServerResponse, FastifyLoggerInstance>, opts: FastifyPluginOptions, next: (err?: Error) => void): void'.
Overload 2 of 3, '(plugin: FastifyPluginAsync<FastifyPluginOptions>, opts?: FastifyRegisterOptions<FastifyPluginOptions>): FastifyInstance<...> & PromiseLike<...>', gave the following error.
Argument of type 'Promise<typeof import(".../node_modules/fastify-formbody/formbody")>' is not assignable to parameter of type 'FastifyPluginAsync<FastifyPluginOptions>'.
Type 'Promise<typeof import(".../node_modules/fastify-formbody/formbody")>' provides no match for the signature '(instance: FastifyInstance<RawServerBase, IncomingMessage | Http2ServerRequest, ServerResponse | Http2ServerResponse, FastifyLoggerInstance>, opts: FastifyPluginOptions): Promise<...>'.
Overload 3 of 3, '(plugin: FastifyPluginCallback<FastifyPluginOptions> | FastifyPluginAsync<FastifyPluginOptions>, opts?: FastifyRegisterOptions<...>): FastifyInstance<...> & PromiseLike<...>', gave the following error.
Argument of type 'Promise<typeof import(".../node_modules/fastify-formbody/formbody")>' is not assignable to parameter of type 'FastifyPluginCallback<FastifyPluginOptions> | FastifyPluginAsync<FastifyPluginOptions>'.
Type 'Promise<typeof import(".../node_modules/fastify-formbody/formbody")>' is not assignable to type 'FastifyPluginAsync<FastifyPluginOptions>'.
```
## Expected behavior
There should be no errors.
We can use `as any` to bypass this problem but not sure it's the best thing to do.
## Your Environment
- *node version*: 14
- *fastify version*: 3.0.1
- *os*: Mac
| https://github.com/fastify/fastify/issues/2403 | https://github.com/fastify/fastify/pull/2494 | 1cf972e500f8d5ab215b2217cc133cca6bb4f269 | 102654ecd9957035fcfe58958752314c0e6ede91 | "2020-07-11T17:21:36Z" | javascript | "2020-08-12T21:29:01Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,385 | ["fastify.d.ts", "test/types/reply.test-d.ts", "test/types/request.test-d.ts", "types/content-type-parser.d.ts", "types/hooks.d.ts", "types/instance.d.ts", "types/reply.d.ts", "types/request.d.ts", "types/route.d.ts", "types/utils.d.ts"] | Type `FastifyReply` body | ## π Feature Proposal
The `send` method from `FastifyReply` accepts a generic parameter `T` ([code here](https://github.com/fastify/fastify/blob/master/types/reply.d.ts#L25)), but it is not used anywhere else
Could we make that `T` parameter part of the `FastifyReply` parameters? `express` is doing something similar here https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/express-serve-static-core/index.d.ts#L505
A strech goal would be to change the types to have a different reply type per status code, so it maps event better to the json schema (not sure this is possible)
## Motivation
Having `T` forwarded into `FastifyReply` would allow for better typings, for example
```
type CustomReply = FastifyReply<{
isTypedReplyBody: boolean;
}>
fastify.get('/', async (request: FastifyRequest, reply: CustomReply) => {
reply.send({isTypedReplyBody: true}) // ok
reply.send({raw: true}) // not ok, ts error
})
``` | https://github.com/fastify/fastify/issues/2385 | https://github.com/fastify/fastify/pull/2389 | f5ca1fac02d61b0280f191b7019deadc20466570 | 87efb7e7d2c27d3d0e5c7c045b15edb18e95a6be | "2020-07-08T08:43:50Z" | javascript | "2020-07-15T14:23:26Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,378 | ["fastify.d.ts", "test/types/fastify.test-d.ts", "test/types/plugin.test-d.ts"] | Investigate how to support `const app = fastify(); await app;` in TypeScript | Related to https://github.com/fastify/fastify/pull/2376
See the test in the PR.
How do we type this behavior?
If its not possible (which I sorta expect but don't know for sure), then we should provide some type-cast option like:
```ts
// untested code ahead do not assume this is the solution :-)
const _app = fastify()
const app = _app as unknown as () => Promise<FastifyInstance>
await app; // resolves FastifyInstance
```
| https://github.com/fastify/fastify/issues/2378 | https://github.com/fastify/fastify/pull/2428 | 2a2be75309a796cbe450fdeb39e0d100c78b98d7 | 6233a8f77fd53da88ef001c4e9d4047cda8a6af0 | "2020-07-07T02:06:34Z" | javascript | "2020-07-23T22:58:59Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,372 | ["docs/Reply.md"] | Unexpected cookies behaviour | <!--
Before you submit an issue we recommend you visit [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify.
**Please read this entire template before posting any issue. If you ignore these instructions
and post an issue here that does not follow the instructions, your issue might be closed,
locked, and assigned the `missing discussion` label.**
-->
## π Bug Report
When the ServerResponse instance (`reply.raw`) is used to respond to the client after setting a cookie, the cookie doesn't appear in the browser.
## To Reproduce
Reproducible example: https://codesandbox.io/s/adoring-solomon-n61yz?file=/src/build.js:589-592
1. Go to the provided server on CodeSanbox: https://n61yz.sse.codesandbox.io/
3. Open the dev tools and enter the cookies viewer in the application tab.
2. Go to `/cookie-2`
3. There is no cookie β
But if you go to `/cookie-1` instead, the cookie will appear. β
```js
// expected
app.get('/cookie-1', (req, reply) => {
reply
.setCookie('session', 'value', { secure: false })
.header('Content-Type', 'text/plain')
.send('ok')
})
// unexpected
app.get('/cookie-2', (req, reply) => {
reply.setCookie('session', 'value', { secure: false })
reply.raw.writeHead(200, { 'Content-Type': 'text/plain' })
reply.raw.write('ok')
reply.raw.end()
})
```
## Expected behavior
In both cases, the client should have the cookie saved on the server-side.
## Your Environment
- *node version*: 10.20.1
- *fastify version*: 3.0.0-rc.5
- *os*: Windows
| https://github.com/fastify/fastify/issues/2372 | https://github.com/fastify/fastify/pull/2553 | 1ce1b308513d2f3e491d8cc2da68b25806e49760 | 875f8a3cf760f363baf1febf5eedb82d1b6da2c8 | "2020-07-05T06:20:28Z" | javascript | "2020-09-14T13:31:20Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,358 | ["test/types/instance.test-d.ts", "types/instance.d.ts"] | Error: Property 'setReplySerializer' does not exist on type 'FastifyInstance' | ## π Bug Report
I'm trying to use setReplySerializer() in my Fastify-powered TypeScript project. However, an error is thrown:
`error TS2339: Property 'setReplySerializer' does not exist on type 'FastifyInstance<Server, IncomingMessage, ServerResponse, FastifyLoggerInstance>'.`
## To Reproduce
Steps to reproduce the behavior:
```js
import * as Fastify from 'fastify';
(async () => {
try {
const server = Fastify.fastify();
// Based upon https://www.fastify.io/docs/master/Server/#setreplyserializer
server.setReplySerializer(function (payload: any, statusCode: any) {
return `my serialized ${statusCode} content: ${payload}`;
});
await server.listen(3000, '0.0.0.0');
} catch (err) {
console.error(err);
}
})();
```
## Expected behavior
No TypeScript error
## Your Environment
- *Node version*: 12
- *Fastify version*: 3.0.0-rc.4
- *TypeScript version*: 3.9.5
- *os*: Linux | https://github.com/fastify/fastify/issues/2358 | https://github.com/fastify/fastify/pull/2400 | da021f14c37b2f9a259d5328416afeb4dcc4252b | 2495ba1d62de9ba0c289463cac0c45809a7bb87b | "2020-06-29T15:14:10Z" | javascript | "2020-07-14T06:06:17Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,316 | ["package.json"] | Validate this context for fastify errorHandler | <!--
Before you submit an issue we recommend you visit [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify.
**Please read this entire template before posting any issue. If you ignore these instructions
and post an issue here that does not follow the instructions, your issue might be closed,
locked, and assigned the `missing discussion` label.**
-->
## π Feature Proposal
Original issue: https://github.com/fastify/fastify/issues/2304
#2306 binds the instance to the errorHandler. We should validate this works in TypeScript land and also include a unit a test. It may require a type fix; it may not - that is the purpose of the validation.
| https://github.com/fastify/fastify/issues/2316 | https://github.com/fastify/fastify/pull/2198 | 457886a136aff1f60a8e2c27dfb35789a78f5b6b | a2859c03cd37904994644936fc8b400dae07da56 | "2020-06-02T19:26:42Z" | javascript | "2020-04-14T07:27:35Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,298 | ["docs/Ecosystem.md"] | Asynchronous local storage support | ## π Feature Proposal
Support for AsyncLocalStorage via an official plugin. If user enables this functionality, then fastify will automatically create ALS scope for every new request that could be populated within standard hooks.
## Motivation
Certain cross-cutting functionality (logging, monitoring, authentication) benefits from threadlocal-like functionality.
`cls-hooked` can be used as a fallback solution for older Node versions.
## Example
```
fastify.register(require('fastify-als'))
fastify.addHook('onRequest', (req, reply, done) => {
fastify.setLocal('user', { id: 'fastifyUser' })
});
fastify.get('/', async (request, reply) => {
return {
user: fastify.getLocal('user')
}
});
```
There is prior art already: https://github.com/thorough-developer/fastify-http-context
Maybe it could be used as a basis for an official plugin, or made an official plugin.
I can work on implementing this if approved. | https://github.com/fastify/fastify/issues/2298 | https://github.com/fastify/fastify/pull/2324 | df40dac9b9e296c13d975c4bb47202610ba282f4 | 09fd065d41ba147726499b5f0cad9d5638b56151 | "2020-05-26T08:58:28Z" | javascript | "2020-06-09T11:24:14Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,288 | ["docs/Server.md", "examples/example.js", "fastify.d.ts", "fastify.js", "test/types/fastify.test-d.ts", "test/types/route.test-d.ts", "test/url-rewriting.test.js", "types/route.d.ts"] | Possible type regression from v2 to v3 | ## π₯ Regression Report
It appears that the type definition for route handlers (`RouteHandlerMethod` in v3) no longer has a binding for `this`. I may be entirely misunderstanding the new types though; the abundance of generics is quite clever, but a little hard to quickly grasp.
## Last working version
Worked up to version: 2.14.1
Stopped working in version: 3.0.0-rc.2
## To Reproduce
This is not strictly correct code, but it should illustrate the point:
Steps to reproduce the behaviour
In the following file, `this` produces an error
```ts
export const handler: RouteHandlerMethod = async function(req, reply) {
const id = req.params.id;
this.log({ id }, 'User deleted')
reply.code(204).send();
}
```
The error is:
```
'this' implicitly has type 'any' because it does not have a type annotation.ts(2683)
```
## Expected behavior
I'd expect this to work as it did in v2, where I used the `RequestHandler` interface, which seems to have been replaced by `RouteHandlerMethod` ?
## Your Environment
- *node version*: 12
- *fastify version*: >=3.0.0
- *os*: Linux
| https://github.com/fastify/fastify/issues/2288 | https://github.com/fastify/fastify/pull/2290 | 8b8485ac5ff56d1ead387f6dd76384f996a2cf8e | 4f3a945871060365117b7ce8eb5d3fb4fd178fef | "2020-05-19T13:49:51Z" | javascript | "2020-05-25T13:20:13Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,279 | ["fastify.js", "test/schema-feature.test.js"] | Can't getSchema() even though getSchemas() "has it" | ## π Bug Report
Schema added inside plugin can't be fetched using getSchema('someid')
## To Reproduce
Steps to reproduce the behavior:
```js
fastify.addSchema({
$id: 'http://example.com/',
type: 'object',
properties: {
hello: { type: 'string' }
}
})
console.log('1 getSchemassssss()', fastify.getSchemas()); // OK
console.log('1 getSchema()', fastify.getSchema('http://example.com/')); // OK
fastify.register((instance, opts, done) => {
instance.addSchema({
$id: 'http://example.com/plugin/',
type: 'object',
properties: {
hello: { type: 'string' }
}
})
console.log('2 getSchemassssss()', instance.getSchemas()); // OK: both schemas
console.log('2 getSchema()', instance.getSchema('http://example.com/')); // OK
console.log('3 getSchema()', instance.getSchema('http://example.com/plugin/')); // NOT OK: undefined
done()
})
```
## Expected behavior
A clear and concise description of what you expected to happen.
```js
instance.getSchema('http://example.com/plugin/') // should return 'http://example.com/plugin/' schema
```
## Your Environment
- *node version*: 12
- *fastify version*: >=3.x
- *os*: Mac | https://github.com/fastify/fastify/issues/2279 | https://github.com/fastify/fastify/pull/2280 | 2f56e10a24ecb70c2c7950bfffd60eda8f7782a6 | 425b68e71c3f88cd16e45b831c6cf017d95bbefa | "2020-05-14T13:48:15Z" | javascript | "2020-05-14T19:44:02Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,265 | ["README.md"] | Remove absolute URL | In our docs, there are some link that refers to `master`
Like https://raw.githubusercontent.com/fastify/fastify/master/docs/Server.md
```
<a href="https://github.com/fastify/fastify/blob/master/docs/Server.md"><code><b>Fastify server</b></code></a>
```
I think we should update all those links to relative ones because if a user browsers old tag in GitHub, he would redirect to `master` causing confusion.
Kudos to @lmammino because the fastify.io site already applies this fix ππ»
----
EDIT checklist of files to fix
- [x] README.md
- [ ] docs\ContentTypeParser.md
- [ ] docs\Errors.md
- [ ] docs\Fluent-Schema.md
- [ ] docs\Getting-Started.md
- [ ] docs\Hooks.md
- [ ] docs\Logging.md
- [ ] docs\Middleware.md
- [ ] docs\Migration-Guide-V3.md
- [ ] docs\Plugins-Guide.md
- [ ] docs\Plugins.md
- [ ] docs\Reply.md
- [ ] docs\Request.md
- [ ] docs\Routes.md
- [x] docs\Server.md
- [ ] docs\TypeScript.md
- [ ] docs\Validation-and-Serialization.md
- [ ] docs\Write-Plugin.md
| https://github.com/fastify/fastify/issues/2265 | https://github.com/fastify/fastify/pull/2274 | 15703f51109d0381e6abed1c4c226f25ceefc4d0 | 82a081dfea3b065492df435cff3d695a36ceb60c | "2020-05-06T17:54:19Z" | javascript | "2020-05-12T14:26:55Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,259 | ["fastify.js", "test/inject.test.js"] | `started` flag for fastify no longer set in v3 on ready() | ## π Bug Report
In v3 running `fastify.ready()` no longer sets `fastify[kState].started` to `true`. This results in `lightMyRequest` Chain returned for a builder to be wrapped into a Promise and prematurely resolved, failing with an error.
## To Reproduce
Steps to reproduce the behavior:
https://github.com/fastify/fastify/pull/2257/files
## Expected behavior
Same code would work in v2. Since this is not listed as a breaking change in migration guide, I assume this is a regression rather than removal of deprecated feature.
## Your Environment
- *node version*: 12
- *fastify version*: 3.0.0-rc1
| https://github.com/fastify/fastify/issues/2259 | https://github.com/fastify/fastify/pull/2257 | a60391e9b6b7b516e24d18f0c5a437db28989ff8 | 09170fe41777ddf821179c4aef60d434d6de1efb | "2020-05-05T15:06:29Z" | javascript | "2020-05-05T20:52:52Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,229 | ["docs/Reply.md", "docs/Server.md", "lib/handleRequest.js", "lib/reply.js", "test/404s.test.js"] | reply.callNotFound not triggering hooks | <!--
Before you submit an issue we recommend you visit [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify.
**Please read this entire template before posting any issue. If you ignore these instructions
and post an issue here that does not follow the instructions, your issue might be closed,
locked, and assigned the `missing discussion` label.**
-->
## π Bug Report
reply.callNotFound() does not trigger hooks
## To Reproduce
Steps to reproduce the behavior see https://github.com/fastify/fastify-static/issues/126, fastify-static use callNotFound internally.
## Expected behavior
The hooks must be called.
## Your Environment
- *node version*: 10, 12, 13
- *fastify version*: >=2.0.0
- *os*: Mac, Windows, Linux
- *any other relevant information* | https://github.com/fastify/fastify/issues/2229 | https://github.com/fastify/fastify/pull/2256 | 1cdf6219ca4ebb015c926f5c467b1bf7b6c88c67 | ae6b57c94cbfcec10b66c4a19d8a62df540486c1 | "2020-04-25T18:16:30Z" | javascript | "2020-05-06T13:28:47Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,223 | ["test/types/route.test-d.ts", "types/reply.d.ts"] | reply.statusCode is not defined in TS type definitions |
## π Bug Report
Docs & implementation have a prop `statusCode`, which isn't available via `FastifyReply<HttpResponse>` definition.
Docs: https://www.fastify.io/docs/latest/Reply/#statuscode
Definitions: https://github.com/fastify/fastify/blob/64296c84b57eb8f6f63bf51579febcfd274a97a5/types/reply.d.ts#L8 | https://github.com/fastify/fastify/issues/2223 | https://github.com/fastify/fastify/pull/2224 | 28fcb5f9438e85031265a9b0ba60bb01791db010 | 2e9994d1c3cb0c61424d624674ec517360542c26 | "2020-04-23T11:39:08Z" | javascript | "2020-04-24T09:38:50Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,214 | ["lib/reply.js", "test/content-length.test.js"] | Error with `content-lenght` header | ## π Bug Report
If in a async handler, an error is thrown and `headers` property contains `content-length` key, the response header `content-length` doesn't match the real response body length
## To Reproduce
```js
'use strict'
const assert = require('assert')
const fastify = require('./fastify')({ log: { level: 'trace' } })
fastify.get('/', async () => {
const error = new Error('MY_ERROR_MESSAGE')
error.headers = {
'content-length': 2
}
throw error
})
fastify.inject({
method: 'GET',
path: '/'
})
.then(response => {
assert.strictEqual(response.headers['content-length'], response.rawPayload.length)
})
```
## Expected behavior
The response `content-length` should not be propagated to
## Your Environment
- *node version*: v12.16.1
- *fastify version*: = 2.13.1
- *os*: Mac
| https://github.com/fastify/fastify/issues/2214 | https://github.com/fastify/fastify/pull/2215 | 121f32a46b9f3d4df2be4e81ea9427386c37eb14 | 6e8035201b07b5a7a7fe2c7722652d50c37e07bb | "2020-04-22T12:02:56Z" | javascript | "2020-04-22T13:51:19Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,203 | ["docs/Hooks.md", "lib/context.js", "lib/hooks.js", "lib/route.js", "test/hooks.test.js", "test/types/hooks.test-d.ts", "types/hooks.d.ts", "types/instance.d.ts", "types/route.d.ts"] | Add an onTimeout hook | ## π Feature Proposal
There are hooks for most events in a request's lifecycle, but I believe that a request that times out doesn't go through the onError or onResponse hooks, so there currently isn't any way to respond to timeouts. This feature proposal is adding an onTimeout hook (or something similar) that would be invoked whenever a request times out.
## Motivation
In our app, we want to know how many currently-outstanding requests there are. That way, when we stop sending requests to one server (to do a rolling update), we can know when the server is fully drained and it's safe to update it. To implement our currently-outstanding-request-counter, we can increment a counter when the request comes in, but without an onTimeout hook, we can't properly decrement the counter. We could manually manage the timeouts out of band, but it would be more convenient to do it all in the context of Fastify hooks.
## Example
```
fastify.addHook('onTimeout', () => counter--)
``` | https://github.com/fastify/fastify/issues/2203 | https://github.com/fastify/fastify/pull/2457 | 21578f56dea6bfd3de1c9a4df497fd535d174221 | 8e2d008c450b29b39aff8aa127e0ed7a10775988 | "2020-04-14T18:49:58Z" | javascript | "2020-08-06T12:35:44Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,169 | ["lib/errors.js", "lib/reply.js", "test/reply-error.test.js"] | Fastify crashes when reply code is not recognized | ## π Bug Report
Fastify crashes when reply code is not recognized.
## To Reproduce
Steps to reproduce the behavior:
Run fastify server that returns an exotic response code.
```js
const fastify = require('fastify')({ logger: true });
fastify.get('/', async (request, reply) => {
reply.code(525); // exotic response code
return { hello: 'world' };
});
const start = async () => {
try {
await fastify.listen(3000);
fastify.log.info(`server listening on ${fastify.server.address().port}`);
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();
```
Make a request to the server
```bash
curl http://localhost:3000
```
The application crashes.
The HTTP response code is 500 and the response body is as follows.
```json
{"statusCode":500,"code":"FST_ERR_BAD_STATUS_CODE","error":"Internal Server Error","message":"FST_ERR_BAD_STATUS_CODE: Called reply with malformed status code"}
```
## Expected behavior
The application should not crash
## Your Environment
- *node version*: v10.19.0
- *fastify version*: 2.13.0
- *os*: Mac
| https://github.com/fastify/fastify/issues/2169 | https://github.com/fastify/fastify/pull/2184 | 08e0a0443cbdd432c87cc0cfaf8f10d54e42ff45 | 8ba959d67c5bc3782eec891cc44bdc1c8ce5d641 | "2020-04-01T05:50:48Z" | javascript | "2020-04-08T09:24:29Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,117 | ["docs/Decorators.md"] | Add docs for explaining the concept of object shapes | Using the decorator defines the shape of request objects. See https://mathiasbynens.be/notes/shapes-ics
_Originally posted by @jsumners in https://github.com/fastify/fastify/issues/2115#issuecomment-590562376_ | https://github.com/fastify/fastify/issues/2117 | https://github.com/fastify/fastify/pull/2127 | ba9086b163ea0e9ac3b4a4ec935cb8e4b64fea6d | 2874af53002dd9fde9ab24e74b90121cb86bc62d | "2020-02-25T13:31:02Z" | javascript | "2020-03-08T02:05:08Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,116 | ["lib/decorate.js", "lib/errors.js", "test/decorator.test.js", "test/internals/decorator.test.js"] | Make decorate* methods throw after server is started. |
## π Feature Proposal
In https://github.com/fastify/fastify/issues/2115, the reporter is trying to decorate the global request object within a route. This is not supported by Fastify, and we should throw if `server.decorate()`, `server.decorateRequest()` or `server.decorateReply()` are called after `.ready()`.
| https://github.com/fastify/fastify/issues/2116 | https://github.com/fastify/fastify/pull/2128 | 2874af53002dd9fde9ab24e74b90121cb86bc62d | 512561f9b868d5ebc5b3cdf9016bf73ae07304ad | "2020-02-24T19:21:03Z" | javascript | "2020-03-08T21:16:10Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,112 | ["lib/route.js", "test/http2/plain.js"] | request.hostname isn't set when using HTTP2 | ## π Bug Report
`request.hostname` isn't set when using HTTP2.
## To Reproduce
`index.js`:
```js
module.exports = async function (fastify, opts) {
fastify.get('/', async (req, r) => r.send(`hostname: ${req.hostname}\n`));
};
module.exports.options = { http2: true };
```
## Expected behavior
Running `fastify start -o index.js` and `curl --http2-prior-knowledge http://localhost:3000` gives:
```
hostname: localhost:3000
```
## Actual behavior
```
hostname: undefined
```
## Your Environment
- *node version*: v13.9.0
- *fastify version*: 2.11.0
- *os*: Windows | https://github.com/fastify/fastify/issues/2112 | https://github.com/fastify/fastify/pull/2113 | 6f79a90703078451f4571ac3e08b815a26753503 | 093947b75dfbb5da784c3714550d4d7ecf9a340f | "2020-02-24T00:37:54Z" | javascript | "2020-02-24T12:10:14Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,104 | ["lib/schemas.js", "lib/symbols.js", "test/hooks.test.js", "test/route.test.js"] | PR-2044 (one schema for multiple routes) introduce breaking change behavior on routes schema resolve. | ## π₯ Regression Report
PR https://github.com/fastify/fastify/pull/2044 breaks https://github.com/SkeLLLa/fastify-oas and probably related to https://github.com/fastify/fastify-swagger/issues/224
Consider you have fastify onRoute hook and save the routes like
```js
const myRouteData = []
fastify.addHook('onRoute', (route) => {
myRouteData.push(route);
});
```
Earlier after `.ready()` method is finished his job, e.g. `await app.ready()`, in `schema` in route object was resolved to actual schema objects.
E.g. if you referenced schemas by id
```js
{
query: 'mySchema#'
}
```
after app is `ready` you could expect an object in `route.schema.querystring`.
However now it's not resolved and still is a string.
## Last working version
Worked up to version: 2.11.0
Stopped working in version: 2.12.0
## To Reproduce
Steps to reproduce the behaviour:
1. Add schema with `fastify.addSchema`
2. Reference that schema in route
Paste your code here:
```js
const routes = []
fastify.addHook('onRoute', (route) => {
// here route.schema should be an object
routes.push(route)
});
await fastify.ready()
// iterate over routes and check if `body`, `params`, etc. are not strings.
```
## Expected behavior
It expects that `route.schema.[body,querystring,params,headers]` will be an resolved object after app is ready. However after that PR it is a string (when schema ids are used)
## Your Environment
- *node version*: 12
- *fastify version*: >=2.12.0
- *os*: Linux
- *any other relevant information*
| https://github.com/fastify/fastify/issues/2104 | https://github.com/fastify/fastify/pull/2108 | 98ca7fd538c1f2ebc0ee5d71272d9dcd3f34601b | 6f79a90703078451f4571ac3e08b815a26753503 | "2020-02-18T11:46:07Z" | javascript | "2020-02-23T17:23:27Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,078 | ["lib/errors.js", "lib/reply.js", "test/reply-error.test.js"] | Truncated error response when using reply.code(undefined) | ## π Bug Report
When setting the response status code to `undefined` inside error handler, response returned is truncated.
This bug was unveiled while working on an issue with `fastifh-gql` [default error handler](https://github.com/mcollina/fastify-gql/blob/174ebb5185e0377acefcac0b0c638b3a575e61e3/lib/routes.js#L58), which set the response code to `err.statusCode`, that could be undefined.
## To Reproduce
[Codesandbox](https://codesandbox.io/s/upbeat-napier-broov?expanddevtools=1&fontsize=14&hidenavigation=1&moduleview=1&theme=dark)
Paste your code here:
```js
const fastify = require("fastify");
const axios = require("axios");
async function start() {
const app = fastify({ logger: true });
app.setErrorHandler(async (err, request, reply) => {
reply.code(undefined);
return { errors: [err.message] };
});
app.get("/", async (request, reply) => {
throw new Error("This message will be truncated");
});
const port = 8080;
try {
await app.listen(port);
} catch (err) {
app.log.error(err);
process.exit(1);
}
await axios(`http://localhost:${port}`);
}
if (require.main === module) {
start();
}
```
You'll get in return:
```js
(node:1727) UnhandledPromiseRejectionWarning: Error: Parse Error
at Socket.socketOnData (_http_client.js:442:20)
at Socket.emit (events.js:198:13)
at addChunk (_stream_readable.js:287:12)
at readableAddChunk (_stream_readable.js:268:11)
at Socket.Readable.push (_stream_readable.js:223:10)
at TCP.onStreamRead (internal/stream_base_commons.js:94:17)
```
On a browser such as Firefox or Chrome, the response is truncated.
## Expected behavior
The response should not be truncated.
## Your Environment
- *node version*: 13.3
- *fastify version*: >=2.11.0
- *os*: Linux
| https://github.com/fastify/fastify/issues/2078 | https://github.com/fastify/fastify/pull/2082 | 14b4e02d3648355987568eccf328a7111558c1b2 | 41cd02fe81f8895ee7fe9de6579ac39438465776 | "2020-02-03T10:16:38Z" | javascript | "2020-02-13T19:35:02Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,075 | ["docs/Hooks.md", "test/hooks-async.js", "test/hooks.test.js"] | Use symbol to denote early termination of request | ## π Feature Proposal
Introduce `Symbol.for('fastify.end-request')` to terminate requests prior to reaching the defined request handler. When this symbol is received from a hook, or any function in the request life _prior_ to the defined request handler, Fastify should issue a `res.send()` that sends any headers and content currently attached to `res` to the requesting client.
This should also take the place of returning `undefined` to signal the same thing. Thus, when `undefined` is received from such a function, a deprecation notice/error/warning should be logged.
## Motivation
As highlighted in https://github.com/fastify/fastify/issues/2070 and https://github.com/fastify/help/issues/135 , it is unclear how one should terminate a request response before reaching the handler.
## Example
```js
fastify.addHook('onRequest', () => {
// do something
return Symbol.for('fastify.end-request')
})
// or
fastify.addHook('onRequest', (req, res, next) => {
// do something
next(null, Symbol.for('fastify.end-request'))
})
// or
fastify.addHook('onRequest', async (req, res) => {
// do something
return Symbol.for('fastify.end-request')
})
```
| https://github.com/fastify/fastify/issues/2075 | https://github.com/fastify/fastify/pull/2079 | c052c21db4b1d8b80eafd3435a6ba4ccdc9f97f8 | aacefcde84334edc0feeb335807bd530a2bcff19 | "2020-02-02T17:19:26Z" | javascript | "2020-02-06T18:05:37Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,070 | ["docs/Errors.md", "lib/errors.js", "lib/hooks.js", "test/hooks.test.js"] | Promise rejection without error |
## π Bug Report
If an async hook returns a `Promise.reject()` the flow continue.
This usage of promise should be avoided at all, let me know if you think this is an `invalid` bug.
Here we should check the `err` param
https://github.com/fastify/fastify/blob/7fa4bddca07aac18e0600cff40d97b95a96ab970/lib/hooks.js#L80-L82
## To Reproduce
Steps to reproduce the behavior:
```js
const fastify = require('./fastify')({ logger: true })
fastify.addHook('onRequest', function (request, reply) {
return Promise.reject()
})
fastify.get('/', async (request, reply) => { return 'hi' })
fastify.listen(3001)
```
## Expected behavior
The rejection should be managed.
_Originally posted by @Eomm in https://github.com/fastify/help/issues/135#issuecomment-580913741_
| https://github.com/fastify/fastify/issues/2070 | https://github.com/fastify/fastify/pull/2074 | 6b3987003fea822feee9eb559e009efbb177ff67 | c052c21db4b1d8b80eafd3435a6ba4ccdc9f97f8 | "2020-01-31T21:19:42Z" | javascript | "2020-02-03T21:11:06Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,065 | ["docs/Errors.md", "lib/handleRequest.js", "test/error-in-post.test.js", "test/sync-routes.test.js"] | Support synchronous routes |
## π Feature Proposal
I propose we call `reply.send()` in synchronous routes if the returned value is not Promise or a Stream.
## Motivation
It seems a lot of newbies to fastify mistake the use of `async`, and we are not providing them a good developer experience.
## Example
```js
'use strict';
module.exports = (server, opts, done) => {
server.get('/', () => {
return "Hello World";
});
done();
};
``` | https://github.com/fastify/fastify/issues/2065 | https://github.com/fastify/fastify/pull/2073 | 798f18526d6199b505141724a6c6ed2804bb80fd | 3486afe04a05c0874c63010f7525361a316905fe | "2020-01-30T14:58:50Z" | javascript | "2020-02-06T18:06:13Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,040 | ["fastify.d.ts", "test/types/hooks.test-d.ts", "test/types/route.test-d.ts", "types/hooks.d.ts", "types/instance.d.ts", "types/middleware.d.ts", "types/route.d.ts"] | v3 type def clarification for `addHook` method | I've been fixing the `hooks.d.ts` part of the new types and I've hit a very difficult snag. We have two hooks `onSend` and `preSerialization` that pass through the `payload` argument to the hook handler. For best type safety, we should allow the user to specify what this is via a generic parameter. But because all of the other hook handlers do not require this generic parameter I cannot just add it to `addHook`.
What I can do is specify the generic parameter from the specific hook handler definition; and then allow the user to pass this through to the `addHook` function. This requires the user to specify the `onSend` and `preSerialization` hooks like so:
```typescript
type TestPayloadType = {
foo: string,
bar: number
}
// equivalent for `onSend`
const preSerializationHook: preSerializationHookHandler<TestPayloadType> = (request, reply, payload, done) => {
// you can ignore this code its just apart of the unit tests
expectType<FastifyRequest>(request)
expectType<FastifyReply>(reply)
expectType<TestPayloadType>(payload)
expectType<(err: FastifyError) => void>(done(new Error()))
expectType<(err: null, res: string) => void>(done(null, 'foobar'))
expectError(done())
}
server.addHook('preSerialization', preSerializationHook)
```
There does not seem to be a way to pass that generic in line:
```typescript
// THIS CODE IS INVALID
type TestPayloadType = {
foo: string,
bar: number
}
// Where would `<TestPayloadType>` go?
server.addHook('preSerialization', (request, reply, payload, done) => {
// ...
})
```
Also, please note that **for all other hooks** the normal way of specifying them will work:
```typescript
server.addHook('onRequest', (request, reply, done) => {
expectType<FastifyRequest>(request)
expectType<FastifyReply>(reply)
expectType<(err?: FastifyError) => void>(done)
})
```
---
I've attempted to write a definition that supports passing the payload generic to the `addHook` method but could not figure it out (i believe it might be impossible). So with all of this considered, **is the previously mention specification okay?** Of course, this will be detailed in the TypeScript documentation with code examples -- and I'll include a special note in the type definition comments (editors bubble these up to the user so they can get more info without leaving the editor).
Lastly, i'm going to make a gist with all of my type def attempts as a reference -- [will add that here when its ready.](https://gist.github.com/Ethan-Arrowood/c0294ae9533a8b1908cf9c1a0e0208c0) <-- check it out. i'll be adding to it with other attempts as I go | https://github.com/fastify/fastify/issues/2040 | https://github.com/fastify/fastify/pull/2042 | b9a6a041d1dfc341600abe16f6ec309f0386c402 | aadefb2e5c4451452c03573e0c8e844812864b19 | "2020-01-15T17:10:05Z" | javascript | "2020-03-19T21:56:36Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,036 | ["docs/Server.md", "fastify.js", "test/request-error.test.js"] | fastify behind haproxy results into "read ECONNRESET" errors | ## π Bug Report
As mentioned in https://github.com/fastify/fastify/blob/master/docs/Recommendations.md we would like to run fastify behind haproxy (for TLS termination and load balancing)
After processing an request proxied over haproxy it throws an ECONNRESET error:
```
{"level":30,"time":1578524093038,"pid":16376,"hostname":"ip-10-64-1-175","reqId":1,"req":{"method":"GET","url":"/check","hostname":"localhost","remoteAddress":"127.0.0.1","remotePort":42838},"msg":"incoming request","v":1}
{"level":30,"time":1578524093045,"pid":16376,"hostname":"ip-10-64-1-175","reqId":1,"res":{"statusCode":200},"responseTime":5.577713999897242,"msg":"request completed","v":1}
{"level":20,"time":1578524093046,"pid":16376,"hostname":"ip-10-64-1-175","err":{"type":"Error","message":"read ECONNRESET","stack":"Error: read ECONNRESET\n at TCP.onStreamRead (internal/stream_base_commons.js:200:27)","errno":"ECONNRESET","code":"ECONNRESET","syscall":"read"},"msg":"client error","v":1}
{"level":30,"time":1578524101311,"pid":16376,"hostname":"ip-10-64-1-175","reqId":2,"req":{"method":"GET","url":"/check","hostname":"localhost","remoteAddress":"127.0.0.1","remotePort":42842},"msg":"incoming request","v":1}
{"level":30,"time":1578524101311,"pid":16376,"hostname":"ip-10-64-1-175","reqId":2,"res":{"statusCode":200},"responseTime":0.34771000035107136,"msg":"request completed","v":1}
{"level":20,"time":1578524101311,"pid":16376,"hostname":"ip-10-64-1-175","err":{"type":"Error","message":"read ECONNRESET","stack":"Error: read ECONNRESET\n at TCP.onStreamRead (internal/stream_base_commons.js:200:27)","errno":"ECONNRESET","code":"ECONNRESET","syscall":"read"},"msg":"client error","v":1}
```
If I bypass haproxy and call directly the NodeJS process this is not happening:
```
{"level":30,"time":1578524117357,"pid":16376,"hostname":"ip-10-64-1-175","reqId":3,"req":{"method":"GET","url":"/check","hostname":"localhost:8337","remoteAddress":"127.0.0.1","remotePort":42850},"msg":"incoming request","v":1}
{"level":30,"time":1578524117357,"pid":16376,"hostname":"ip-10-64-1-175","reqId":3,"res":{"statusCode":200},"responseTime":0.4655680004507303,"msg":"request completed","v":1}
{"level":30,"time":1578524120839,"pid":16376,"hostname":"ip-10-64-1-175","reqId":4,"req":{"method":"GET","url":"/check","hostname":"localhost:8337","remoteAddress":"127.0.0.1","remotePort":42852},"msg":"incoming request","v":1}
{"level":30,"time":1578524120840,"pid":16376,"hostname":"ip-10-64-1-175","reqId":4,"res":{"statusCode":200},"responseTime":0.3121840003877878,"msg":"request completed","v":1}
```
Error is triggered via HTTP.Server 'clientError' - logged at https://github.com/fastify/fastify/blob/master/fastify.js#L417 - also I would ask why errors are just logged as "debug" severity?
## To Reproduce
To exclude other possible errors like network issues node and haproxy are running on the same machine.
As HTTP client for testing I used cmd line CURL on same machine. I could reproduce the same also with links & lynx browser on CMD line. Also it was reproducible from remote.
1. Node with fastify on Port 8337 (simple.ts)
2. Haproxy with haproxy.cfg on Port 80
3. "curl http://localhost/check" (over haproxy, causes that issue)
4. "curl http://localhost:8337/check" (directly NodeJS, no issue)
(Error is only logged on logger level >= debug)
*simple.ts*
```js
import * as fastify from 'fastify';
const app = fastify({
logger: {
level: 'trace',
},
trustProxy: true,
});
app.get('*', (_req, reply) => {
reply.send('foo');
});
app.listen(8337, '0.0.0.0');
```
*haproxy.cfg* (reduced version out of Recommendations.md)
```haproxy
global
log /dev/log syslog
maxconn 4096
chroot /var/lib/haproxy
user haproxy
group haproxy
defaults
log global
mode http
option httplog
option dontlognull
option forwardfor
retries 3
option redispatch
maxconn 2000
timeout connect 5000
timeout client 50000
timeout server 50000
frontend proxy
bind 0.0.0.0:80
default_backend fastify
backend fastify
server local 127.0.0.1:8337
```
## Expected behavior
I also tested if this also occurs with just node HTTP.server implementation, I couldn't reprodue it. Also I couldn't see this behavior with express.js.
There should be no "Error: read ECONNRESET\n at TCP.onStreamRead"
Looks for me if something is trying to read on a already ended connection?
## Your Environment
- *node version*: 12.14.1
- *fastify version*: 2.11.0
- *os*: Linux, debian buster - also reproduced on Mac
- *haproxy version*: 1.8.19-1+deb10u1
- *curl version*: 7.64.0
- *any other relevant information*
| https://github.com/fastify/fastify/issues/2036 | https://github.com/fastify/fastify/pull/2268 | d335a7a729c0bbba4a3ae0fbe08254fd410f86ea | d8feb2323c00d49a16b48401a2f7e8fcfbbb0338 | "2020-01-09T08:31:41Z" | javascript | "2020-05-08T13:05:43Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,030 | ["fastify.d.ts", "test/types/index.ts"] | Add generic parameter for Reply send method | Based on a discussion in https://github.com/fastify/help/issues/125 a good feature for the type system (current and future) would be to add a generic parameter to the `reply.send` method to allow the user to specify the payload type being passed in. It is currently set to `any` see [v2](https://github.com/fastify/fastify/blob/master/fastify.d.ts#L180) and [v3](https://github.com/fastifyf/fastify/blob/next/types/reply.d.ts#L22).
This is not a breaking feature to the type system so it should not block the v3 release. | https://github.com/fastify/fastify/issues/2030 | https://github.com/fastify/fastify/pull/2032 | 620a7a073b8eca1d7be5cae22fad6e7f9348623b | e6c63c33327084b6feaac147ab6e82d5d0ae47b9 | "2020-01-07T21:19:09Z" | javascript | "2020-01-08T17:39:12Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 2,024 | ["lib/schemas.js", "test/route.test.js"] | I cant use one schema for two different routes | π Bug Report
when I want too set my schema to different routs I get this error
FastifyError [FST_ERR_SCH_DUPLICATE]: FST_ERR_SCH_DUPLICATE: Schema with 'querystring' already present!
## To Reproduce
create a schema with query and add it to different routes
```js
this is my schema
"sportSite_sportSiteSessionForGetAllSchema": {
"params": {
"type": "object",
"required": [ "sportSiteUUID" ],
"properties": {
"sportSiteUUID": { "type": "string", "format": "uuid" }
}
},
"query": {
"type": "object",
"properties": {
"pageSize": { "type": "integer", "maximum": sportSiteWorkPlanMaxPage },
"pageNumber": { "type": "integer" }
}
}
}
and my routes
fastify.get( "/:sportSiteUUID/sessions/userType/customer", {
"schema": sportSite_sportSiteSessionForGetAllSchema
}, httpHandlers.getAllSportSiteSessionsForSportSiteForCustomerHandler );
fastify.get( "/:sportSiteUUID/sessions/userType/provider", {
"schema": sportSite_sportSiteSessionForGetAllSchema,
"preHandler": [
fastify.authenticate( fastify.tokenUtil ),
fastify.authorizeByRoles( [ "provider" ] ),
fastify.authorizeResource( fastify, ( req ) => req.params.sportSiteUUID )
]
}, httpHandlers.getAllSportSiteSessionsForSportSiteForProviderHandler );
```
- *node version*: 13.5
- *fastify version*: >=2.11.0
- *os*: Windows
| https://github.com/fastify/fastify/issues/2024 | https://github.com/fastify/fastify/pull/2044 | 5258f421a32592396d9e9999812f6c6096ccf6db | 62f21b1211dab665cccca4dec966169ae548ba1b | "2020-01-05T13:20:44Z" | javascript | "2020-01-18T11:34:40Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,993 | ["lib/handleRequest.js", "test/http2/head.test.js", "test/internals/handleRequest.test.js"] | Under Nodejs v13.5.0, Fastify HTTP2.0 use .finished which could be true when .writableEnded is false | Maybe it is a nodejs bug, but in handleRequest.js:
function preValidationCallback (err, request, reply) {
if (reply.sent === true || reply.res.**finished** === true) return
if (err != null) {
reply.send(err)
return
}
...
function preHandlerCallback (err, request, reply) {
if (reply.sent || reply.res.**finished** === true) return
if (err != null) {
reply.send(err)
return
}
...
when handle **HEAD** request, reply.res.**finished** will be true, but reply.res.**writableEnded** is false.
use .finished would cause client pending because server early returns.
I changed my node_modules/fastify source, use **writableEnded**, then everything is Ok.
Since .finished is Deprecated in Nodejs v13.4.0, I think use .writableEnded (if it exists) is the right thing. | https://github.com/fastify/fastify/issues/1993 | https://github.com/fastify/fastify/pull/2233 | 4f88ce7034597199ed4b5e6c76819cfd80e6d487 | a0b5673447de3451e43ef46960045ce352b4ae32 | "2019-12-19T04:12:52Z" | javascript | "2020-04-27T10:12:24Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,973 | ["package.json"] | Use Pino v6 | In fastify v3 we will use Pino v6. | https://github.com/fastify/fastify/issues/1973 | https://github.com/fastify/fastify/pull/2163 | f1cfcadbe201f98137a5b2a9ee1159215b5d81e5 | f40ca9729eec4d8632fd3397b691a31c0ad3c671 | "2019-12-09T09:23:22Z" | javascript | "2020-03-28T14:37:39Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,970 | ["docs/Hooks.md", "fastify.js", "lib/hooks.js", "lib/route.js", "lib/symbols.js", "test/hooks.test.js"] | new scope for fastify plugin | ## π¬ Questions and Help
I try to encapsule the rate-limit plugin to its own fastify instance.
```js
const fastify = require("fastify");
const fastifyRateLimit = require("fastify-rate-limit");
const ioredis_1 = require("ioredis");
const server = fastify();
const start = async () => {
server.get('/', async (request, response) => {
return { hello: 'world' };
});
server.register(async (instance, opts) => {
instance.register(fastifyRateLimit, {
max: 1,
timeWindow: 10 * 1000,
redis: new ioredis_1.default()
});
instance.get('/limit1', async (request, response) => {
return { limit: 1 };
});
instance.get('/limit2', async (request, response) => {
return { limit: 2 };
});
});
server.get('/broken', async (request, response) => {
return { broken: true };
});
await server.listen(3000);
};
start()
.catch((e) => {
throw e;
});
```
## Expected behavior
Only the routes `/limit1` and `/limit2` should have the rate-limit plugin "attached".
But currently the route `/broken` is also limited by the rate-limiter, while the `/` is without any rate-limit.
As far as I understood the `.register` function it shall gave you a new scope of fastify that you can modify without effecting the "outer" fastify instance.
## Your Environment
- *node version*: 13.3.0
- *fastify version*: 2.11.0
- *fastify-rate-limit version*: 3.0.1
- *os*: Linux | https://github.com/fastify/fastify/issues/1970 | https://github.com/fastify/fastify/pull/2004 | 747311e820b2c964b2d01dadbcba425617787065 | 80d87c959fcbb2ae00295bebbd1d912c97f64184 | "2019-12-08T15:08:57Z" | javascript | "2019-12-27T16:02:46Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,960 | ["lib/route.js", "package.json", "test/route.test.js", "test/schemas.test.js"] | Schema and route declaration order conflict. | ## π Bug Report
Initially opened at https://github.com/fastify/fastify-cors/issues/47 because upgrading the cors plugin caused shared schemas to fail. I looped through the debugger many times and I think I found the issue.
This was because the `fastify-cors` plugin starting from version 2.2.0 added a default line that hide OPTIONS routes from swagger. [Relevant commit](https://github.com/fastify/fastify-cors/commit/a28da42af1f92b819241c975436bade27f5dc9b2).
If a shared schema was added after the cors plugin was registered, and used in a subsequent route declaration, the list of schemas attached to the default schema compiler (ajv in this case) is already set, and additional referenced schemas can't be found.
To see what I mean, set a breakpoint at line 229 in `fastify/lib/route.js` where `buildSchema` is called. If you inspect `this[kSchemaCompiler]`'s bound `this`'s `_refs` field, you'll see that in the cases where it works, there is a schema keyed `https://example.com/bson/objectId`; in cases where it doesn't, this property is missing.
## To Reproduce
Referring to the sample code below...
Running the script as is will throw a `FST_ERR_SCH_BUILD` error, saying it cannot find the `https://example.com/bson/objectId` ref.
Any of the options will make it work, and show the right properties in `_refs`.
1. Comment out the line below `1a`.
2. Comment out `2`, and uncomment `3`.
3. Move `1` below `2`.
```js
const fastify = require('fastify')({ logger: true });
const fp = require('fastify-plugin');
/**
* 1. An example of a plugin declaring a route with one of the options
* being a schema option.
*/
fastify.get(
'/',
/**
* 1a. The option line below is one of the cause of the issue.
*/
{ schema: { random: 'options' } },
(req, reply) => reply.send(),
);
/**
* 2. Registration of shared schemas used throughout the server in a plugin.
*/
fastify.register(fp(async f => f.addSchema({
$id: 'https://example.com/bson/objectId',
type: 'string',
pattern: '\\b[0-9A-Fa-f]{24}\\b',
})));
/**
* 3. Registration of shared schemas used throughout the server inline.
*/
// fastify.addSchema({
// $id: 'https://example.com/bson/objectId',
// type: 'string',
// pattern: '\\b[0-9A-Fa-f]{24}\\b',
// });
/**
* 4. Another route declaration, this time using the shared schema in $ref-way form.
*/
fastify.get(
'/:id',
{
schema: {
params: {
type: 'object',
properties: {
id: { $ref: 'https://example.com/bson/objectId#' },
},
},
},
},
(req, reply) => reply.send({ hello: req.params.id }),
);
/**
* Start the server.
*/
fastify.listen('1337', '127.0.0.1');
```
## Expected behavior
Perhaps this is an expected behavior but it seems like a gotcha since there shouldn't be any conflict between declaring routes/schemas in any order, as long as the declared schema happens before the route that uses it and is in its inherited scope.
## Your Environment
- *node version*: 12
- *fastify version*: >=2.9.0
- *os*: Mac/Linux
- *any other relevant information*
| https://github.com/fastify/fastify/issues/1960 | https://github.com/fastify/fastify/pull/2077 | a272f153946fbe5134ff2d55d1e9526967e0ad41 | 0b50f38df033ae112d5043cdf21297c7562f608e | "2019-11-28T16:38:42Z" | javascript | "2020-03-02T09:04:59Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,914 | ["test/types/hooks.test-d.ts", "test/types/instance.test-d.ts", "test/types/route.test-d.ts", "types/error.d.ts", "types/hooks.d.ts", "types/instance.d.ts"] | TypeScript FastifyError inherits from Error instead of ErrnoException | ## π Bug Report
`FastifyError` inherits from `Error` (JavaScript type), but it can hold other properties as `NodeJS.ErrnoException` (Node.js Error type) defined.
`ErrnoException` in:
Node.js v6:
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v6/base.d.ts#L327
Node.js v8: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v8/base.d.ts#L375
```js
export interface ErrnoException extends Error {
errno?: number;
code?: string;
path?: string;
syscall?: string;
stack?: string;
}
```
Error:
```js
interface Error {
stack?: string;
}
```
## To Reproduce
Steps to reproduce the behavior:
`error` argument is a `FastifyError` instance. We need to cast to Node.js `ErrnoException` to get code property.
```js
fastify.setErrorHandler((error, request, reply): void => {
const e = error as NodeJS.ErrnoException
if (e.code === 'ECONNREFUSED' || e.code === 'ENOTFOUND') {
reply.send(new create.ServiceUnavailable())
```
## Expected behavior
If `interface FastifyError extends ErrnoException` then we needn't cast error.
See: https://github.com/fastify/fastify/blob/master/fastify.d.ts#L51
```js
fastify.setErrorHandler((error, request, reply): void => {
if (error.code === 'ECONNREFUSED' || error.code === 'ENOTFOUND') {
reply.send(new create.ServiceUnavailable())
```
## Your Environment
- *node version*: 10
- *fastify version*: >=2.10.0
- *os*: Mac
| https://github.com/fastify/fastify/issues/1914 | https://github.com/fastify/fastify/pull/2337 | 68f1ac6b727d938287d5d8dba114ea8c8c63f4ee | 25d7ba2b86d00dd68c4bbb5648ee3706a6b8dafe | "2019-10-24T13:41:50Z" | javascript | "2020-06-18T19:21:02Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,900 | ["README.md"] | Fluent Schema not shown in documentations? | Before you submit an issue we recommend you drop into the [Gitter community](https://gitter.im/fastify) or [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify.
**Please read this entire template before posting any issue. If you ignore these instructions
and post an issue here that does not follow the instructions, your issue might be closed,
locked, and assigned the `missing discussion` label.**
## π Bug Report
Had me scratching my head if this is an experimental feature since it's hidden. Is this expected?
<img width="550" alt="Screen Shot 2019-10-18 at 7 24 01 AM" src="https://user-images.githubusercontent.com/7200153/67054822-5d962000-f178-11e9-85a5-420e0e9a8d68.png">
| https://github.com/fastify/fastify/issues/1900 | https://github.com/fastify/fastify/pull/1903 | 3991088b4b22fb04263d197eb271973390f28e6a | 7f8c3f2ba7c7f01cd24397976e545dd57e924d47 | "2019-10-17T23:26:00Z" | javascript | "2019-10-19T19:30:36Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,884 | ["fastify.js", "package.json", "test/404s.test.js"] | 404 with not encoded URI path parameter | ## π Bug Report
If I send a wrong path parameter without appling an `encodedURI` I get a 404 response and a warn:
```
{"level":30,"time":1570179820901,"pid":21956,"hostname":"MSPIGOLON5591","reqId":3,"req":{"method":"GET","url":"/%25what%","remotePort":53476},"msg":"incoming request","v":1}
{"level":40,"time":1570179820902,"pid":21956,"hostname":"MSPIGOLON5591","reqId":3,"msg":"the default handler for 404 did not catch this, this is likely a fastify bug, please report it","v":1}
{"level":40,"time":1570179820902,"pid":21956,"hostname":"MSPIGOLON5591","reqId":3,"msg":"ΓΓΆΓΆΓΓΆΓΓΓΆΓ / (ACL|BIND|CHECKOUT|CONNECT|COPY|DELETE|GET|HEAD|LINK|LOCK|M-SEARCH|MERGE|MKACTIVITY|MKCALENDAR|MKCOL|MOVE|NOTIFY|OPTIONS|PATCH|POST|PROPFIND|PROPPATCH|PURGE|PUT|REBIND|REPORT|SEARCH|SOURCE|SUBSCRIBE|TRACE|UNBIND|UNLINK|UNLOCK|UNSUBSCRIBE)\n ΓΓΆΓΆΓΓΆΓΓΓΆΓ * (ACL|BIND|CHECKOUT|CONNECT|COPY|DELETE|GET|HEAD|LINK|LOCK|M-SEARCH|MERGE|MKACTIVITY|MKCALENDAR|MKCOL|MOVE|NOTIFY|OPTIONS|PATCH|POST|PROPFIND|PROPPATCH|PURGE|PUT|REBIND|REPORT|SEARCH|SOURCE|SUBSCRIBE|TRACE|UNBIND|UNLINK|UNLOCK|UNSUBSCRIBE)\n","v":1}
```
## To Reproduce
```js
const fastify = require('fastify')({ logger: true })
fastify.get('/:strangeId', (req, reply) => {
reply.send({ strangeId: req.params.strangeId })
})
fastify.listen(3000)
```
```
curl -X GET http://localhost:3000/%what% -H 'Accept: */*' -H 'Accept-Encoding: gzip, deflate'
-H 'Connection: keep-alive' -H 'Host: localhost:3000' -H 'User-Agent: PostmanRuntime/7.17.1'
```
All work with an encoded path param:
```
curl -X GET http://localhost:3000/%25what%25 -H 'Accept: */*' -H 'Accept-Encoding: gzip, deflate'
-H 'Connection: keep-alive' -H 'Host: localhost:3000' -H 'User-Agent: PostmanRuntime/7.17.1'
```
## Expected behaviour
I wouldn't expect a 404.
With a plain server, the URL is:
```
{ req: '/%what%' }
{ req: '/%25what%25' }
```
```js
const http = require('http')
const server = http.createServer(function manageResponse (req, res) {
console.log({ req: req.url })
res.end('hello')
})
server.listen(3000)
```
## Your Environment
- *node version*: 12
- *fastify version*: 2.9
- *os*: Windows
| https://github.com/fastify/fastify/issues/1884 | https://github.com/fastify/fastify/pull/1888 | 7c4c7d64ee84655cfa00d34e450404cf10145662 | 11d286e4cab57d466b58385ee7a091abcc5348cc | "2019-10-04T09:08:15Z" | javascript | "2019-10-26T10:11:30Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,881 | ["fastify.d.ts", "lib/schemas.js", "package.json", "test/schemas.test.js", "test/types/index.ts"] | Broken JSON Schema resolution | ## π Bug Report
When using a reference to a full schema definition, instead of to a sub resource of the referenced schema, Fastify's schema resolution incorrectly mutates the reference name. The result is that it cannot find the referenced schema.
## To Reproduce
Steps to reproduce the behavior:
Paste your code here:
```js
'use strict';
const AJV = require('ajv');
const ajv = new AJV();
ajv.addSchema({
$id: 'urn:schema:foo',
definitions: {
foo: { type: 'string' }
},
type: 'object',
properties: {
foo: { $ref: '#/definitions/foo' }
}
});
ajv.addSchema({
$id: 'urn:schema:response',
type: 'object',
properties: {
bar: { $ref: 'urn:schema:foo' }
}
});
const fastify = require('fastify')();
fastify.setSchemaCompiler(schema => ajv.compile(schema));
fastify.setSchemaResolver(name => ajv.getSchema(name).schema);
fastify.route({
path: '/',
method: 'GET',
schema: {
response: {
'2xx': ajv.getSchema('urn:schema:response').schema
}
},
handler(req, reply) {
reply.send({ bar: { foo: 'bar' } });
}
});
fastify.inject({ url: '/' }, (err, response) => {
if (err) {
throw err;
}
console.log(response.body);
});
```
## Expected behavior
The `urn:schema:foo` reference should resolve to an object schema.
## Cause
https://github.com/fastify/fastify/blob/89dd7493c06774600635b010ebac6a622bfd42f2/lib/schemas.js#L110
Notice that on this line the value of `refValue` will be `'urn:schema:foo'`. Since this string does not have a `#` character, the line will execute `refValue.slice(0, -1)` which will yield `'urn:schema:fo'`.
| https://github.com/fastify/fastify/issues/1881 | https://github.com/fastify/fastify/pull/1882 | 89dd7493c06774600635b010ebac6a622bfd42f2 | f199f9ff8723d7c04b93c6db3a941f675365d75b | "2019-10-01T18:15:47Z" | javascript | "2019-10-05T16:04:10Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,871 | ["lib/schemas.js", "test/internals/schemas.test.js"] | Creates invalid schema | ## π Bug Report
Fastify with fastify-swagger creates invalid swagger schema. It should not contain $id fields.
## To Reproduce
https://repl.it/repls/HoarseCoolEditor
And you'll got
```json
...
"paths": {
"/first": {
"get": {
"responses": {
"200": {
"schema": {
"type": "array",
"items": {
"type": "object",
"properties": {
"a": {
"type": "number"
}
},
"$id": "A"
}
},
"description": "Default Response"
}
}
}
},
}
...
```
Notice the `responses.200.schema.items.$id`. Swagger generates error like
```
should NOT have additional properties
additionalProperty: $id
```
## Your Environment
- *node version*: 8
- *fastify version*: 2.8.0
- *os*: Linux
I plan to create PR with fix a bit later | https://github.com/fastify/fastify/issues/1871 | https://github.com/fastify/fastify/pull/1872 | 72451e901227048707fff157df6abeab6d5e23a8 | 5c00909721c16ceafae46da9378017a401ed96be | "2019-09-25T11:22:47Z" | javascript | "2019-09-25T15:36:26Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,870 | [".github/workflows/ci.yml"] | Coveralls GH action posts too many comments | Currently, the coveralls GitHub action is posting too many comments in the pull request. I've checked our coveralls configuration, and the comments are disabled. I'm not even sure that problem is caused by the [coveralls GitHub action](https://github.com/coverallsapp/github-action).
A couple of examples of pr with too many comments: https://github.com/fastify/fastify/pull/1869 https://github.com/fastify/fastify/pull/1867
Related: https://github.com/fastify/fastify/issues/1847 https://github.com/fastify/fastify/pull/1853 https://github.com/coverallsapp/github-action/issues/5 | https://github.com/fastify/fastify/issues/1870 | https://github.com/fastify/fastify/pull/1918 | 16173896d42ce34f7af5d702587d9487762cf444 | d0e78d16d151db402332386127385fed8541a9cb | "2019-09-24T08:20:12Z" | javascript | "2019-11-02T21:07:16Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,864 | ["docs/Reply.md", "docs/Routes.md", "lib/reply.js", "test/async-await.js", "test/internals/reply.test.js", "test/promises.test.js"] | Async style with reply.send | ## π Bug Report
`repl.send` inside an async function has created a lot of headache.
- https://github.com/fastify/fastify/issues/238
- https://github.com/fastify/fastify/issues/238
- https://github.com/fastify/fastify/issues/548
- https://github.com/fastify/fastify/issues/1131
with https://github.com/fastify/fastify-static/issues/110 we have another issue. The issue ist that an error is logged because `sendFile` doesn't accept a callback or return a promise. The route is fulfilled to `undefined` before the file was sent. This behaviour doesn't agree with https://github.com/fastify/fastify/blob/master/docs/Routes.md#promise-resolution.
Due to the current implementation every decorator/plugin which calls `.send` under the hood must provide a callback or promise to the consumer. If they don't the handler can't use async/await and will loose the control over the response.
## Expected behavior
**In the longer term we change the api.**
```js
// the data flow isnt determined by the function return value (koajs be like)
fastify
.get('/', async (request, reply) => {
reply.body = await data()
repl.body = sync()
});
```
**In short term:**
Teach and update the docs that you can use only `reply.send` in async/await if you still return a promise that controls the asynchronous operation.
```js
until send is called
fastify
.get('/', async (request, reply) => {
return op().then(reply.send)
});
```
or we recommend to not use `rely.send` at all in async functions | https://github.com/fastify/fastify/issues/1864 | https://github.com/fastify/fastify/pull/1869 | 5a61f3e0b163bfa51df846e29cce6519c94ef5ee | 0e39b83c3bde8a9cb6531ad2dbe960be75199e1d | "2019-09-21T08:30:37Z" | javascript | "2019-09-25T12:01:49Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,855 | ["docs/Server.md", "docs/Validation-and-Serialization.md", "fastify.js", "lib/errors.js", "lib/handleRequest.js", "lib/route.js", "lib/schemas.js", "lib/symbols.js", "lib/validation.js", "test/schemas.test.js"] | Using custom AJV breaks resolving references | ## π Bug Report
When using a custom AJV instance as described in the documentation (https://www.fastify.io/docs/latest/Validation-and-Serialization/#schema-compiler) one cannot provide a schema with references as a response schema.
## To Reproduce
```js
'use strict';
const AJV = require('ajv');
const ajv = new AJV();
ajv.addSchema({
$id: 'urn:schema:foo',
definitions: {
foo: { type: 'string' }
},
type: 'object',
properties: {
foo: { $ref: '#/definitions/foo' }
}
});
ajv.addSchema({
$id: 'urn:schema:response',
type: 'object',
properties: {
foo: { $ref: 'urn:schema:foo#/definitions/foo' }
}
});
const fastify = require('fastify')();
fastify.setSchemaCompiler(schema => ajv.compile(schema));
fastify.route({
path: '/',
method: 'GET',
schema: {
response: {
'2xx': ajv.getSchema('urn:schema:response').schema
}
},
handler(req, reply) {
reply.send({ foo: 'bar' });
}
});
fastify.inject({ url: '/' }, (err, response) => {
if (err) {
throw err;
}
console.log(response.body);
});
```
## Expected behavior
The route should register and resolve references correctly.
Paste the results here:
```js
/private/tmp/17/fastify-custom-ajv/index.js:44
throw err;
^
FastifyError [FST_ERR_SCH_BUILD]: FST_ERR_SCH_BUILD: Failed building the schema for GET: /, due error Cannot read property '$ref' of undefined
at Object.afterRouteAdded (/private/tmp/17/fastify-custom-ajv/node_modules/.registry.npmjs.org/fastify/2.8.0/node_modules/fastify/lib/route.js:224:37)
at after (/private/tmp/17/fastify-custom-ajv/node_modules/.registry.npmjs.org/fastify/2.8.0/node_modules/fastify/lib/route.js:165:25)
at Object._encapsulateThreeParam (/private/tmp/17/fastify-custom-ajv/node_modules/.registry.npmjs.org/avvio/6.2.2/node_modules/avvio/boot.js:417:7)
at Boot.callWithCbOrNextTick (/private/tmp/17/fastify-custom-ajv/node_modules/.registry.npmjs.org/avvio/6.2.2/node_modules/avvio/boot.js:339:5)
at Boot._after (/private/tmp/17/fastify-custom-ajv/node_modules/.registry.npmjs.org/avvio/6.2.2/node_modules/avvio/boot.js:230:26)
at Plugin.exec (/private/tmp/17/fastify-custom-ajv/node_modules/.registry.npmjs.org/avvio/6.2.2/node_modules/avvio/plugin.js:89:17)
at Boot.loadPlugin (/private/tmp/17/fastify-custom-ajv/node_modules/.registry.npmjs.org/avvio/6.2.2/node_modules/avvio/plugin.js:175:10)
at Task.release (/private/tmp/17/fastify-custom-ajv/node_modules/.registry.npmjs.org/fastq/1.6.0/node_modules/fastq/queue.js:127:16)
at worked (/private/tmp/17/fastify-custom-ajv/node_modules/.registry.npmjs.org/fastq/1.6.0/node_modules/fastq/queue.js:169:10)
at toLoad.finish (/private/tmp/17/fastify-custom-ajv/node_modules/.registry.npmjs.org/avvio/6.2.2/node_modules/avvio/plugin.js:178:7)
```
## Your Environment
- *node version*: 10.16.3
- *fastify version*: 2.8.0
- *os*: Mac
| https://github.com/fastify/fastify/issues/1855 | https://github.com/fastify/fastify/pull/1858 | 27ff97cad56f01d5b5bcb71c0b919a04ae0b3a6a | 4cf5c338edcdece7272f9935da91e6b1080eb190 | "2019-09-17T21:05:21Z" | javascript | "2019-09-27T08:55:30Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,847 | [".github/workflows/ci.yml", ".github/workflows/package-manager-ci.yml", ".github/workflows/website.yml", ".travis.yml", "README.md", "docs/LTS.md"] | Leverage Github Actions |
## π Feature Proposal
We have Github Actions enabled in this repo! What can we do with them?
One thing that would be nice is to move the trigger to CircleCI for deploying the website.
Moreover, we can actually redo the automation for the [website](https://github.com/fastify/website) using actions!
@lmammino and maybe others, would it be nice to have these here?
| https://github.com/fastify/fastify/issues/1847 | https://github.com/fastify/fastify/pull/1853 | d50e173c6ca46a43c2b357de759cdf793ed6a1ee | 03d2408a2d910df2a4625c590fe15ee1ae0e277a | "2019-09-10T16:38:55Z" | javascript | "2019-09-20T13:31:53Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,823 | ["lib/fourOhFour.js", "test/404s.test.js", "test/logger.test.js", "test/route-prefix.test.js"] | Do not create an Error for the default 404 route |
## π Feature Proposal
Creating an `Error` is costly, and we should be able to avoid that in https://github.com/fastify/fastify/blob/d48c6a21f21d72b7683808aa88b3fdcd2e0478db/lib/fourOhFour.js#L53. Moreover, it complicates debugging (see #1822 for details).
| https://github.com/fastify/fastify/issues/1823 | https://github.com/fastify/fastify/pull/1826 | 05c0329cce02d3124e868d13c4072b9c6c9981ad | 76c8879a07aa221f98aa9df89cfdac7ad844c521 | "2019-08-26T09:21:15Z" | javascript | "2019-08-28T13:05:59Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,776 | ["lib/handleRequest.js", "package.json", "test/hooks-async.js"] | async preValidation hook does not abort request | ## π Bug Report
When calling `reply.send` within an async preValidation hook, this does not abort the request and thus emits a `Response has already been sent` error. Related: #677
According to the linked issue and pr, it should have been fixed, however it doesn't seem to be (At least for me):
## To Reproduce
Hook:
```js
fastify.addHook("preValidation", async function (request, reply) {
reply.code(403).send({error: "unauthenticated"});
});
```
Handler:
```js
module.exports = function (fastify, opts, next) {
fastify.get("/", {}, async (request, reply) => {
// This gets still executed, and reply.sent is true here
});
next();
}
```
## Expected behavior
The handler should not get called.
## Your Environment
- *node version*: 10.16.0
- *fastify version*: >=2.5.0
- *os*: Windows, Linux
| https://github.com/fastify/fastify/issues/1776 | https://github.com/fastify/fastify/pull/1778 | b856f07facb6667d8e34e6e352d76a0c53b452f9 | 2996fd83042084a2ecccc38b6fa123ec87546eec | "2019-07-30T07:39:42Z" | javascript | "2019-07-31T07:59:03Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,733 | ["lib/handleRequest.js", "package.json", "test/hooks-async.js"] | Lifecycle is not interrupted when onSend executes asynchronously | ## π Bug Report
When an instance `onSend` hook executes asynchronously, responding from a route hook does not always prevent the route handler from being called.
## To Reproduce
#### Setup
1. `npm init -y && npm i -S [email protected]`
2. Add the code from [this gist](https://gist.github.com/ericmacfa/e5331a632464ec4530c7a42617b67f45) to index.js
<details>
<summary>Bare-bones snippet</summary>
<p>
```js
const fastify = require('fastify')();
// This issue occurs with both callback and promise based `onSend` hooks
fastify.addHook('onSend', (request, reply, payload, done) => {
setTimeout(() => {
done(null, payload);
}, 50);
});
fastify.route({
method: 'GET',
path: '/',
preHandler: async function(request, reply) {
console.log('GET / -> preHandler()');
reply.redirect('/login');
},
handler: function(request, reply) {
console.log('GET / -> handler() !! This should never be shown !!');
reply.send({ hello: 'world' });
}
});
fastify.route({
method: 'GET',
path: '/login',
handler: function(request, reply) {
console.log('GET /login -> handler()');
reply.send('Please log in\n');
}
});
fastify.listen(3000);
```
</p>
</details>
3. `node ./index.js`
#### Steps to reproduce
1. `curl -L localhost:3000` (Or via a browser, postman, etc.)
2. Notice that the `/` route handler was called, even though we responded in the `preHandler` hook.
```
server listening on port 3000
GET / -> preHandler()
GET / -> handler() !! This should never be shown !!
GET /login -> handler()
```
#### Additional notes (from gist code comments)
- This issue occurs when either the callback or the promise based `onSend` hook is used.
- This issue occurs when the promise based `preHandler` hook is used, but not when the callback based version is used.
## Expected behavior
1. `curl -L localhost:3000`
2. The handler for the `/` route should not be called.
```
server listening on port 3000
GET / -> preHandler()
GET /login -> handler()
```
## Your Environment
- _node version_: `10.16.0`
- _fastify version_: `2.6.0`
- _os_: Mac
| https://github.com/fastify/fastify/issues/1733 | https://github.com/fastify/fastify/pull/1778 | b856f07facb6667d8e34e6e352d76a0c53b452f9 | 2996fd83042084a2ecccc38b6fa123ec87546eec | "2019-07-05T15:39:44Z" | javascript | "2019-07-31T07:59:03Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,680 | ["docs/Reply.md"] | Error thrown from a hook is not propagating to custom error handler | If you throw an error from a hook it is not propagated to the custom error handler.
## To Reproduce
```js
const fastify = require('fastify')();
fastify.setErrorHandler(async (error, request, reply) => {
console.log("Im in error handler", error);
reply.code(401).send({ error });
});
fastify.addHook("preValidation", async (request) => {
console.log("Im in pre validation");
throw { detail: "Token is not valid" };
});
fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
});
fastify.listen(3000, err => {
if (err) throw err;
const port = fastify.server.address().port;
console.log(`server listening on ${port}`)
});
```
```curl --request GET --url http://localhost:3000/```
## Expected behavior
The error should propagate to custom `errorHandler` and respond with 401 in this case.
## Current behavior
Not propagated error handler and responding with 200 `{ detail: "Token is not valid" }` as the body.
## Environment
- *node version*: 10
- *fastify version*: 2.4.1
- *os*: Mac
| https://github.com/fastify/fastify/issues/1680 | https://github.com/fastify/fastify/pull/2126 | a8d5448862bcff5c616ac863d73e2b3f2e00d6e6 | ba9086b163ea0e9ac3b4a4ec935cb8e4b64fea6d | "2019-05-30T14:33:41Z" | javascript | "2020-03-07T17:14:05Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,672 | ["lib/route.js", "test/route-prefix.test.js"] | Setting ignoreTrailingSlash and prefixTrailingSlash prevents avvio from throwing an error | ## π Bug Report
Setting `ignoreTrailingSlash: true` on main Fastify instance and registering a plugin with tralingSlash prefixed path (`prefix: '/attendances/'`), prevents avvio from crashing on startup with `AssertionError [ERR_ASSERTION]: Method 'GET' already declared for route '/v1/attendances/'` error.
As you can see on [repro repo](https://github.com/fox1t/afterRouteAdded-swallowed-error), in this case fastify registers two routes on the inner plugin and starts the server:
* GET /v1/attendances/
* GET /v1/attendances//
After the server is ready, calling `/v1/attendances//` route will result in `TypeError: Cannot read property 'length' of undefined` in [`/lib/hooks.js:65:32`](https://github.com/fastify/fastify/blob/master/lib/hooks.js#L65).
This happens because [`/lib/route.js#L246`](https://github.com/fastify/fastify/blob/master/lib/route.js#L246) is never reached for `/v1/attendances//` and therefore some pre* hooks (preParsing, preValidation preSerialization) are never set to `null`. There is only a default for preHandler hook [lib/context.js#L16](https://github.com/fastify/fastify/blob/master/lib/context.js#L16). The others are supposed to be set in afterRouteAdded function, but for `/v1/attendances//` the execution goes in [lib/route.js#L228](https://github.com/fastify/fastify/blob/master/lib/route.js#L228) (as already pointed out with an`AssertionError [ERR_ASSERTION]: Method 'GET' already declared for route '/v1/attendances/'`).
The `done` callback is located in avvio [plugin.js#L98](https://github.com/mcollina/avvio/blob/master/plugin.js#L98) and when called for `/v1/attendances//` it finds the `completed===true` because of `/v1/attendances/`. The bug is generated on [lib/route.js#L144](https://github.com/fastify/fastify/blob/master/lib/route.js#L144) since it calls `afterRouteAdded.call` two times in a row. In fact, using a non default value for `prefixTrailingSlash` (so `slash` or `no-slash`) it works as expected.
## To Reproduce
Clone this [repo](https://github.com/fox1t/afterRouteAdded-swallowed-error):
`npm i`
`npm run dev`
call the `/v1/attendances//` rout using postman or similar.
## Expected behavior
Avvio must stop loading the plugin and throwing `AssertionError [ERR_ASSERTION]: Method 'GET' already declared for route '/v1/attendances/'` error.
## Your Environment
- *node version*: 10
- *fastify version*: >=2.4.1
- *os*: Mac
| https://github.com/fastify/fastify/issues/1672 | https://github.com/fastify/fastify/pull/1675 | fc52dc3813dec514b8bb374660818e0a52ec13b6 | ecea232ae596fd0eb06a5b38080e19e4414bd942 | "2019-05-24T13:22:14Z" | javascript | "2019-06-04T15:36:31Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,668 | ["docs/TypeScript.md", "fastify.d.ts", "types/instance.d.ts", "types/plugin.d.ts", "types/register.d.ts", "types/reply.d.ts", "types/request.d.ts"] | TypeScript Schema Example Documentation | ## π Feature Proposal
The upcoming type refactor #1569 references a documentation example of how to declare strict schema types. This issue will track that documentation addition. (It'll also be the start to the next stage of v3 types which is improving the TS docs and examples).
## Motivation
TypeScript support π
## Example
Copied from PR comment:
> It looks like others are solving this problem by using [json-schema-to-typescript](https://www.npmjs.com/package/json-schema-to-typescript). This [article](https://spin.atomicobject.com/2018/03/26/typescript-data-validation/) discusses how a specific team is using it directly with Ajv too!
>
> I'm thinking about using a similar approach to the Pino type definition. I'll use a JSDoc comment on FastifySchema in order to tell the user if they'd like more strict schema type support they should utilize the above library -- this should point to a detailed write up in our own documentation to show users exactly how to make it work with Fastify (or a custom fastify plugin that can do this automatically for the user) | https://github.com/fastify/fastify/issues/1668 | https://github.com/fastify/fastify/pull/1966 | feb0bb6d3cf338fca35ced347d904e7a6a45eafa | f7bc276008b85215e4901ad271cf29dea69c8af4 | "2019-05-23T16:54:12Z" | javascript | "2020-03-29T14:33:32Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,667 | ["fastify.d.ts", "test/types/index.ts"] | TypeScript RouteOptions interface generics missing defaults | ## π Bug Report
Working with routes definition I found that `RouteOptions` interface hasn't default generics declared. (https://github.com/fastify/fastify/blob/master/fastify.d.ts#L266) as opposed to `RouteShorthandOptions`(https://github.com/fastify/fastify/blob/master/fastify.d.ts#L230) that it extends from.
Is this a wanted behavior? I think this is too verbose since it forces to pass every time a route is declared a full set of same generics: `RouteOptions<Server, IncomingMessage, ServerResponse>`.
## To Reproduce
Removing generics (`<Server, IncomingMessage, ServerResponse>`) TypeScript pops a compiler error:
`Generic type 'RouteOptions<HttpServer, HttpRequest, HttpResponse, Query, Params, Headers, Body>' requires between 3 and 7 type arguments.`
```ts
import { Server, IncomingMessage, ServerResponse } from 'http'
import { RouteOptions, RouteShorthandOptions } from 'fastify'
const listAttendance: RouteOptions<Server, IncomingMessage, ServerResponse> = {
method: 'GET',
url: '/',
handler: (req, reply) => {
reply.send([])
},
}
const listAttendances: RouteShorthandOptions = {}
```
## Expected behavior
Adding the defaults to `RouteOptions` the error goes away. I think this is the desirable behavior.
Paste the results here:
```ts
/**
* Route configuration options such as "url" and "method"
*/
interface RouteOptions<
HttpServer = http.Server,
HttpRequest = http.IncomingMessage,
HttpResponse = http.ServerResponse,
Query = DefaultQuery,
Params = DefaultParams,
Headers = DefaultHeaders,
Body = DefaultBody
>
extends RouteShorthandOptions<
HttpServer,
HttpRequest,
HttpResponse,
Query,
Params,
Headers,
Body
> {
method: HTTPMethod | HTTPMethod[]
url: string
handler: RequestHandler<HttpRequest, HttpResponse, Query, Params, Headers, Body>
}
```
## Your Environment
- *node version*: 10
- *fastify version*: 2.4.1
- *os*: Mac
| https://github.com/fastify/fastify/issues/1667 | https://github.com/fastify/fastify/pull/1669 | 712337d6be084b8fc6dca88923eb9cbe6c205b13 | 1958c74a2bc2e96d3892254904f485985bc57330 | "2019-05-23T15:07:46Z" | javascript | "2019-05-24T13:29:37Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,662 | [".npmignore"] | Git folder was included in v2.4.0 | Hi!
In v2.4.0 NPM package `.git` folder was included and this can cause 2 issue
- Security issue (may be?)
- Installation fails (after installing fastify v2.4.0)
You can see direct NPM folder online at [here](https://unpkg.com/[email protected]/)
Have a nice day! | https://github.com/fastify/fastify/issues/1662 | https://github.com/fastify/fastify/pull/1663 | a6fa039939ee9f9317f9ef7739f265e45f2427b2 | 5d442c54970797a985eaad981abca2342eae23f9 | "2019-05-22T09:20:17Z" | javascript | "2019-05-22T09:37:38Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,658 | [".npmignore", ".travis.yml", "README.md", "docs/LTS.md"] | Remove Travis CI from next branch | As title says. I think the azure-pipelines CI is much better than Travis; I see no reason to continue using the service going forward. | https://github.com/fastify/fastify/issues/1658 | https://github.com/fastify/fastify/pull/1670 | 05ed74244d6050aaa87a615df7e9c6f8506e20df | 98658080df2d1d26b45d8752958399d2eac48707 | "2019-05-19T19:05:25Z" | javascript | "2019-06-01T21:01:11Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,656 | ["fastify.js", "test/route-hooks.test.js"] | Make logs (errors, warnings) useful | Before you submit an issue we recommend you drop into the [Gitter community](https://gitter.im/fastify) or [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify.
**Please read this entire template before posting any issue. If you ignore these instructions
and post an issue here that does not follow the instructions, your issue might be closed,
locked, and assigned the `missing discussion` label.**
## π Bug Report
A clear and concise description of what the bug is.
Logs aren't useful, especially for beginners.
## To Reproduce
Steps to reproduce the behavior:
Use fastify as backend with some plugins.
My log:
```sh
[Server]: Warning: The route option `beforeHandler` has been deprecated, use `preHandler` instead
at beforeHandlerWarning (/Users/dalisoft/Desktop/Dev Env from null/fastifydevenv/node_modules/fastify/lib/warnings.js611)
at Object.afterRouteAdded (/Users/dalisoft/Desktop/Dev Env from null/fastifydevenv/node_modules/fastify/fastify.js4909)
at /Users/dalisoft/Desktop/Dev Env from null/fastifydevenv/node_modules/fastify/fastify.js42729
at Object.encapsulateThreeParam (/Users/dalisoft/Desktop/Dev Env from null/fastifydevenv/nodemodules/avvio/boot.js4197)
at Boot.callWithCbOrNextTick (/Users/dalisoft/Desktop/Dev Env from null/fastifydevenv/node_modules/avvio/boot.js3415)
at Boot.after (/Users/dalisoft/Desktop/Dev Env from null/fastifydevenv/nodemodules/avvio/boot.js23226)
at Plugin.exec (/Users/dalisoft/Desktop/Dev Env from null/fastifydevenv/node_modules/avvio/plugin.js8917)
at Boot.loadPlugin (/Users/dalisoft/Desktop/Dev Env from null/fastifydevenv/node_modules/avvio/plugin.js17510)
at Task.release (/Users/dalisoft/Desktop/Dev Env from null/fastifydevenv/node_modules/fastq/queue.js12716)
at worked (/Users/dalisoft/Desktop/Dev Env from null/fastifydevenv/node_modules/fastq/queue.js16910)
at /Users/dalisoft/Desktop/Dev Env from null/fastifydevenv/node_modules/avvio/plugin.js1787
at done (/Users/dalisoft/Desktop/Dev Env from null/fastifydevenv/node_modules/avvio/plugin.js1365)
at check (/Users/dalisoft/Desktop/Dev Env from null/fastifydevenv/node_modules/avvio/plugin.js1477)
at processTicksAndRejections (internal/process/task_queues.js829)
```
## Expected behavior
A clear and concise description of what you expected to happen.
Logs should show which plugin or where warning/error happened.
## Your Environment
- *node version*: 12
- *fastify version*: >=2.0.0
- *os*: Mac
- [repository](https://github.com/dalisoft/fastify-dev-env)
| https://github.com/fastify/fastify/issues/1656 | https://github.com/fastify/fastify/pull/1657 | dd059016134f97fa8b8509e373dbc0b8194455a4 | 1f3c0de979ed8e6edf2e30c9a8594d85d4299ee9 | "2019-05-18T09:38:19Z" | javascript | "2019-05-19T10:13:14Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,652 | ["package.json"] | An in-range update of flatstr is breaking the build π¨ |
## The dependency [flatstr](https://github.com/davidmarkclements/flatstr) was updated from `1.0.11` to `1.0.12`.
π¨ [View failing branch](https://github.com/fastify/fastify/compare/master...fastify:greenkeeper%2Fflatstr-1.0.12).
This version is **covered** by your **current version range** and after updating it in your project **the build failed**.
flatstr is a direct dependency of this project, and **it is very likely causing it to break**. If other packages depend on yours, this update is probably also breaking those in turn.
<details>
<summary>Status Details</summary>
- β
**continuous-integration/travis-ci/push:** The Travis CI build passed ([Details](https://travis-ci.org/fastify/fastify/builds/533373028?utm_source=github_status&utm_medium=notification)).
- β
**coverage/coveralls:** First build on greenkeeper/flatstr-1.0.12 at 99.355% ([Details](https://coveralls.io/builds/23431007)).
- β **fastify.fastify:** [7 errors / 6 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β
**fastify.fastify (Windows_yarn node_8_x):** [0 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β
**fastify.fastify (Windows_yarn node_10_x):** [0 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β
**fastify.fastify (Windows_yarn node_11_x):** [0 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β **fastify.fastify (Windows_yarn node_12_x):** [1 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β
**fastify.fastify (macOS_yarn node_8_x):** [0 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β
**fastify.fastify (macOS_yarn node_10_x):** [0 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β
**fastify.fastify (macOS_yarn node_11_x):** [0 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β
**fastify.fastify (macOs_npm node_6_x):** [0 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β
**fastify.fastify (macOS_yarn node_12_x):** [0 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β
**fastify.fastify (macOs_npm node_8_x):** [0 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β
**fastify.fastify (Linux_Yarn node_8_x):** [0 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β
**fastify.fastify (macOs_npm node_10_x):** [0 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β
**fastify.fastify (Linux_Yarn node_10_x):** [0 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β
**fastify.fastify (macOs_npm node_11_x):** [0 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β
**fastify.fastify (macOs_npm node_12_x):** [0 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β
**fastify.fastify (Linux_Yarn node_11_x):** [0 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β
**fastify.fastify (Linux_Yarn node_12_x):** [0 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β
**fastify.fastify (Windows_NPM node_6_x):** [0 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β **fastify.fastify (Linux_npm node_6_x):** [2 errors / 2 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β
**fastify.fastify (Windows_NPM node_8_x):** [0 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β
**fastify.fastify (Linux_npm node_8_x):** [0 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β
**fastify.fastify (Windows_NPM node_10_x):** [0 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β **fastify.fastify (Linux_npm node_10_x):** [2 errors / 2 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β **fastify.fastify (Linux_npm node_11_x):** [2 errors / 2 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β
**fastify.fastify (Windows_NPM node_11_x):** [0 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β
**fastify.fastify (Linux_npm node_12_x):** [0 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
- β
**fastify.fastify (Windows_NPM node_12_x):** [0 errors / 0 warnings](https://dev.azure.com/fastify/16bca441-2e2c-4036-b359-402bd9231591/_build/results?buildId=1596)
</details>
---
<details>
<summary>Commits</summary>
<p>The new version differs by 3 commits.</p>
<ul>
<li><a href="https://urls.greenkeeper.io/davidmarkclements/flatstr/commit/94d5343a6197cdedf90fe7fbcf6dff2b80e0d550"><code>94d5343</code></a> <code>1.0.12</code></li>
<li><a href="https://urls.greenkeeper.io/davidmarkclements/flatstr/commit/543c4513bbd490a9eb2b797419f1fd4240adb190"><code>543c451</code></a> <code>found a new flattenning method which is faster than the current solution</code></li>
<li><a href="https://urls.greenkeeper.io/davidmarkclements/flatstr/commit/869e4a3caa05faf494015e3afe4e18c0dc8b217c"><code>869e4a3</code></a> <code>win support for benchmarks</code></li>
</ul>
<p>See the <a href="https://urls.greenkeeper.io/davidmarkclements/flatstr/compare/1b63eebba9e88c7d21d1643055e22aa830b3e12b...94d5343a6197cdedf90fe7fbcf6dff2b80e0d550">full diff</a></p>
</details>
<details>
<summary>FAQ and help</summary>
There is a collection of [frequently asked questions](https://greenkeeper.io/faq.html). If those donβt help, you can always [ask the humans behind Greenkeeper](https://github.com/greenkeeperio/greenkeeper/issues/new).
</details>
---
Your [Greenkeeper](https://greenkeeper.io) Bot :palm_tree:
| https://github.com/fastify/fastify/issues/1652 | https://github.com/fastify/fastify/pull/1653 | f627bbf5b35bfb9f5d91f8d3a83275f1f437e616 | 6e4e662bc51c8e5dd5aa960efb8575e183fd7e6a | "2019-05-16T15:15:20Z" | javascript | "2019-05-16T19:34:26Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,620 | ["package.json"] | Cannot access with ip | `localhost:8080` can work but `[ipv4]:8080`.
Express.js can work properly. | https://github.com/fastify/fastify/issues/1620 | https://github.com/fastify/fastify/pull/4581 | c6a40ebe3ec9aaa2886d8ba7646fea88559412f6 | 2e9526e6245421570a5ef54d3676421f617dc4d7 | "2019-04-30T08:07:19Z" | javascript | "2023-02-13T15:35:50Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,592 | ["docs/Reply.md"] | set status code to 302 on res.redirect by default. | ## π Feature Proposal
Right now fastify `redirect` method set the status code only to `302` when it's not set before. I would like to have this changed and make it act like `express` does. What express does is: set the status code to `302` when `redirect` is called. You can still sent an other code by providing it in the redirect like so: `res.redirect(404, '/login')`.
## Motivation
Right now I'm using the [nestjs](https://github.com/nestjs/nest) framework. Nest currently supports multiple routing libraries such as `express` and `fastify`. `nestjs` is setting the http status code default to `200` or `201` depending on the type of request (`GET`, `POST`). When I'm redirecting the request with `redirect` it returns it with a status of `200` instead of `302` this forms an issue because the browser won't redirect.
I hope we could change `fastify` to set the status to `302` by default when `redirect` is called. You could still sent a custom code by putting it like: `res.redirect(404, '/not-found')`.
| https://github.com/fastify/fastify/issues/1592 | https://github.com/fastify/fastify/pull/2121 | a378dd583dfc2ae0f705e09b449aa6a636c639b2 | 350f00b6bf508b40c1f6bb5fa1a9e81b1b09ef3a | "2019-04-13T01:38:32Z" | javascript | "2020-02-28T11:38:34Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,587 | ["docs/Hooks.md", "fastify.js", "lib/fourOhFour.js", "lib/hooks.js", "lib/route.js", "test/hooks-async.test.js"] | Enable to set all hooks (including .use middlewares) in route() | ## π Feature Proposal
Currently we do not expose an API to add `onRequest` and route specific middlewares, however our codebase can definitely support them. Adding them would ensure an higher level of flexibility combined with the new `onRoute`Β hook.
Missing things:
* [x] `onRequest` - done in https://github.com/fastify/fastify/pull/1594
* [ ] `onSend`
* [ ] `onError`
* [x] `onResponse`
* [ ] middlewares
## Example
Please provide an example for how this feature would be used.
```js
app.route({
method: 'GET',
async onRoute (req, reply) { },
middlewares: [function (req, res, next) {
next()
}]
}, async (req, reply) => {})
```
| https://github.com/fastify/fastify/issues/1587 | https://github.com/fastify/fastify/pull/2005 | f47b3d2e174d71c2443c9425cb3eddf7f63815fb | 747311e820b2c964b2d01dadbcba425617787065 | "2019-04-10T11:38:47Z" | javascript | "2019-12-27T11:56:20Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,560 | ["lib/initialConfigValidation.js", "test/internals/initialConfig.test.js"] | Azure Pipeline Failing | ## π₯ Regression Report
Branch master
Azure says:
> should be equal
Error: should be equal
at Test.t (test/internals/initialConfig.test.js:154:7)
at loop (node_modules/function-loop/index.js:46:15)
Travis agree but says more:
> test/internals/initialConfig.test.js ................ 58/59
Return an error if options do not match the validation schema
not ok should be equal
--- wanted
+++ found
-FST_ERR_INIT_OPTS_INVALID: Invalid initialization options: 'should be boolean'
+FST_ERR_INIT_OPTS_INVALID: Invalid initialization options: '[ 'should be boolean' ]'
I clean the dep in my local environment and I replicated the error.
npm outdated before reinstalling fastify: there wasn't the issue
```
Package Current Wanted Latest Location
@types/node 11.10.4 11.12.0 11.12.0 fastify
@typescript-eslint/eslint-plugin 1.4.2 1.5.0 1.5.0 fastify
@typescript-eslint/parser 1.4.2 1.5.0 1.5.0 fastify
autocannon 3.2.0 3.2.1 3.2.1 fastify
avvio 6.1.1 6.2.1 6.2.1 fastify
fast-json-stringify 1.11.3 1.12.0 1.12.0 fastify
fluent-schema 0.6.1 0.6.2 0.7.0 fastify
helmet 3.15.1 3.16.0 3.16.0 fastify
hsts 2.1.0 2.2.0 2.2.0 fastify
ienoopen 1.0.0 1.1.0 1.1.0 fastify
joi 12.0.0 12.0.0 14.3.1 fastify
pino 5.11.1 5.12.0 5.12.0 fastify
split2 3.1.0 3.1.1 3.1.1 fastify
tap 12.5.3 12.6.1 12.6.1 fastify
tap-mocha-reporter 3.0.9 3.0.9 4.0.1 fastify
typescript 3.3.3333 3.3.4000 3.3.4000 fastify
```
npm outdated after the reinstall (and the error show up):
```
Package Current Wanted Latest Location
fluent-schema 0.6.2 0.6.2 0.7.0 fastify
joi 12.0.0 12.0.0 14.3.1 fastify
tap-mocha-reporter 3.0.9 3.0.9 4.0.1 fastify
```
I will check deeply late today if someone can't work on it sooner than me
| https://github.com/fastify/fastify/issues/1560 | https://github.com/fastify/fastify/pull/1561 | 9ee4ecda4f953376fa3143d46bf3ab1d6da8acb1 | fc388633f6e1f5e250f06ee41bcfa0650c10ccdd | "2019-03-29T08:00:44Z" | javascript | "2019-03-29T09:34:34Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,553 | ["lib/schemas.js", "test/shared-schemas.test.js"] | Server.close() mutates used shared schemas | ## π Bug Report
I've encountered this super weird bug. It seems that if you use a shared schema in an endpoint schema, then shut down the server, the shared schema will get mutated somehow :man_shrugging:
## To Reproduce
```js
const t = require("tap");
const fastify = require("fastify");
const sharedSchema = {
$id: "schema",
type: "object",
properties: {
message: { type: "string" }
}
};
const endpointSchema = {
response: {
"2xx": "schema#" // not referencing the shared schema does resolve the issue
}
};
const setup = () => {
const server = fastify();
server.addSchema(sharedSchema);
server.get("/", { schema: endpointSchema }, async (request, reply) => {
reply.send();
});
return server;
};
t.test("$id", async t => {
const server = await setup();
t.ok(sharedSchema.$id); // passes
await server.close();
t.ok(sharedSchema.$id); // fails
});
```
I need to admit that it took a while to find out what causes the issue. This is a complete mystery to me. Why does this happen?
## Expected behavior
I expected the schemas not to be mutated because... who on earth would expect that? :smile: I see that most examples in the docs imply creating the schema explicitly in the parameter (not storing it in a variable), but as I'm starting to have a bunch of shared schemas I'd rather move them to separate files for less code clutter.
## Your Environment
- *node version*: v10.15.1
- *fastify version*: 1.14.1
- *os*: Linux
| https://github.com/fastify/fastify/issues/1553 | https://github.com/fastify/fastify/pull/1565 | d98629b36b5dedfaa9385c99f9c913f2fe6ad944 | 5de74406dbff5cba90516f6c9f499ea9d5e70e1b | "2019-03-24T23:15:40Z" | javascript | "2019-04-03T19:19:51Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,551 | ["docs/Logging.md", "docs/Request.md", "lib/context.js", "lib/logger.js", "lib/reply.js", "lib/request.js", "lib/route.js", "test/internals/handleRequest.test.js"] | Logger: serialize Fastify objects instead of Node.js | Since Fastify v2 we can access our `Request` and `Reply` objects anywhere, it could be a useful enhancement *(unfortunately it is a breaking change)* update our logger serializers to handle our objects instead of Node.js core ones.
Thoughts?
Related: https://github.com/fastify/fastify/issues/1548
/cc @fastify/fastify
| https://github.com/fastify/fastify/issues/1551 | https://github.com/fastify/fastify/pull/2017 | 94bcf373cf5ff05fda5dddfb31b480b6e2f7d7ca | 8f210861cfe8f49c601ae57605933bf6851c648e | "2019-03-23T13:23:51Z" | javascript | "2020-01-03T17:28:58Z" |
closed | fastify/fastify | https://github.com/fastify/fastify | 1,542 | ["docs/Server.md"] | Update Server#logger to discuss custom logger option | The [Server#logger](https://www.fastify.io/docs/latest/Server/#logger) doc section lists 3 options for the logger server option. I believe the `pinoInstance` option should be expanded (or a new, 4th option should be added) to tell the user they can define or use their own custom logger as long as it follows the rules set forth by our code (I believe it needs a certain list of methods and an optional serializer list for `req`, `res`, and `err`). | https://github.com/fastify/fastify/issues/1542 | https://github.com/fastify/fastify/pull/1577 | c79d90e3a9762723509f25955649580e80eb5b68 | 62dc95651f2725a14ead5805d48af4594570fc5c | "2019-03-15T06:00:35Z" | javascript | "2019-04-12T20:35:48Z" |
Subsets and Splits