Skip to content

Commit

Permalink
Merge branch 'main' of github.com:fastify/fastify into (fastify#4439)…
Browse files Browse the repository at this point in the history
…-Access-handler-name-add-properties-to-req-route-options
  • Loading branch information
cesarvspr committed Dec 28, 2022
2 parents 398b158 + 003eae6 commit d869181
Show file tree
Hide file tree
Showing 10 changed files with 114 additions and 10 deletions.
7 changes: 7 additions & 0 deletions docs/Guides/Ecosystem.md
Expand Up @@ -220,6 +220,10 @@ section.
plugin to authenticate HTTP requests based on api key and signature
- [`fastify-appwrite`](https://github.com/Dev-Manny/fastify-appwrite) Fastify
Plugin for interacting with Appwrite server.
- [`fastify-at-mysql`](https://github.com/mateonunez/fastify-at-mysql) Fastify
MySQL plugin with auto SQL injection attack prevention.
- [`fastify-at-postgres`](https://github.com/mateonunez/fastify-at-postgres) Fastify
Postgres plugin with auto SQL injection attack prevention.
- [`fastify-auth0-verify`](https://github.com/nearform/fastify-auth0-verify):
Auth0 verification plugin for Fastify, internally uses
[fastify-jwt](https://npm.im/fastify-jwt) and
Expand Down Expand Up @@ -387,6 +391,9 @@ section.
- [`fastify-lured`](https://github.com/lependu/fastify-lured) Plugin to load lua
scripts with [fastify-redis](https://github.com/fastify/fastify-redis) and
[lured](https://github.com/enobufs/lured).
- [`fastify-lyra`](https://github.com/mateonunez/fastify-lyra)
A plugin to implement [Lyra](https://github.com/LyraSearch/lyra) search engine
on Fastify.
- [`fastify-mailer`](https://github.com/coopflow/fastify-mailer) Plugin to
initialize and encapsulate [Nodemailer](https://nodemailer.com)'s transporters
instances in Fastify.
Expand Down
19 changes: 19 additions & 0 deletions docs/Reference/Reply.md
Expand Up @@ -674,6 +674,15 @@ fastify.get('/streams', function (request, reply) {
reply.send(stream)
})
```
When using async-await you will need to return or await the reply object:
```js
fastify.get('/streams', async function (request, reply) {
const fs = require('fs')
const stream = fs.createReadStream('some-file', 'utf8')
reply.header('Content-Type', 'application/octet-stream')
return reply.send(stream)
})
```

#### Buffers
<a id="send-buffers"></a>
Expand All @@ -689,6 +698,16 @@ fastify.get('/streams', function (request, reply) {
})
```

When using async-await you will need to return or await the reply object:
```js
const fs = require('fs')
fastify.get('/streams', async function (request, reply) {
fs.readFile('some-file', (err, fileBuffer) => {
reply.send(err || fileBuffer)
})
return reply
})
```
#### Errors
<a id="errors"></a>

Expand Down
20 changes: 17 additions & 3 deletions docs/Reference/Server.md
Expand Up @@ -1011,6 +1011,9 @@ Note that the array contains the `fastify.server.address()` too.
#### getDefaultRoute
<a id="getDefaultRoute"></a>

**Notice**: this method is deprecated and should be removed in the next Fastify
major version.

The `defaultRoute` handler handles requests that do not match any URL specified
by your Fastify application. This defaults to the 404 handler, but can be
overridden with [setDefaultRoute](#setdefaultroute). Method to get the
Expand All @@ -1023,14 +1026,25 @@ const defaultRoute = fastify.getDefaultRoute()
#### setDefaultRoute
<a id="setDefaultRoute"></a>

**Note**: The default 404 handler, or one set using `setNotFoundHandler`, will
never trigger if the default route is overridden. This sets the handler for the
**Notice**: this method is deprecated and should be removed in the next Fastify
major version. Please, consider to use `setNotFoundHandler` or a wildcard
matching route.

The default 404 handler, or one set using `setNotFoundHandler`, will
never trigger if the default route is overridden. This sets the handler for the
Fastify application, not just the current instance context. Use
[setNotFoundHandler](#setnotfoundhandler) if you want to customize 404 handling
instead. Method to set the `defaultRoute` for the server:
instead.

This method sets the `defaultRoute` for the server. Note that, its purpose is
to interact with the underlying raw requests. Unlike other Fastify handlers, the
arguments received are of type [RawRequest](./TypeScript.md#rawrequest) and
[RawReply](./TypeScript.md#rawreply) respectively.

```js
const defaultRoute = function (req, res) {
// req = RawRequest
// res = RawReply
res.end('hello world')
}

Expand Down
3 changes: 2 additions & 1 deletion lib/contentTypeParser.js
Expand Up @@ -70,6 +70,7 @@ ContentTypeParser.prototype.add = function (contentType, opts, parserFn) {
if (contentTypeIsString) {
this.parserList.unshift(new ParserListItem(contentType))
} else {
contentType.isEssence = contentType.source.indexOf(';') === -1
this.parserRegExpList.unshift(contentType)
}
this.customParsers.set(contentType.toString(), parser)
Expand Down Expand Up @@ -389,7 +390,7 @@ function compareContentType (contentType, parserListItem) {
}

function compareRegExpContentType (contentType, essenceMIMEType, regexp) {
if (regexp.source.indexOf(';') === -1) {
if (regexp.isEssence) {
// we do essence check
return regexp.test(essenceMIMEType)
} else {
Expand Down
2 changes: 1 addition & 1 deletion lib/request.js
Expand Up @@ -211,7 +211,7 @@ Object.defineProperties(Request.prototype, {
},
routeSchema: {
get () {
warning.emit('FSTDEP014')
warning.emit('FSTDEP015')
return this[kRouteContext][kPublicRouteContext].schema
}
},
Expand Down
2 changes: 2 additions & 0 deletions lib/route.js
Expand Up @@ -89,9 +89,11 @@ function buildRouting (options) {
hasRoute,
prepareRoute,
getDefaultRoute: function () {
warning.emit('FSTDEP014')
return router.defaultRoute
},
setDefaultRoute: function (defaultRoute) {
warning.emit('FSTDEP014')
if (typeof defaultRoute !== 'function') {
throw new FST_ERR_DEFAULT_ROUTE_INVALID_TYPE()
}
Expand Down
9 changes: 5 additions & 4 deletions lib/warnings.js
Expand Up @@ -25,12 +25,13 @@ warning.create('FastifyDeprecation', 'FSTDEP012', 'Request#context property acce

warning.create('FastifyDeprecation', 'FSTDEP013', 'Direct return of "trailers" function is deprecated. Please use "callback" or "async-await" for return value. The support of direct return will removed in `fastify@5`.')

warning.create('FastifyDeprecation', 'FSTDEP014', 'You are accessing the deprecated "request.routeSchema" property. Use "request.routeOptions.schema" instead. Property "req.routeSchema" will be removed in `fastify@5`.')
warning.create('FastifyDeprecation', 'FSTDEP014', 'You are trying to set/access the default route. This property is deprecated. Please, use setNotFoundHandler if you want to custom a 404 handler or the wildcard (*) to match all routes.')

warning.create('FastifyDeprecation', 'FSTDEP015', 'You are accessing the deprecated "request.routeConfig" property. Use "request.routeOptions.config" instead. Property "req.routeConfig" will be removed in `fastify@5`.')
warning.create('FastifyDeprecation', 'FSTDEP015', 'You are accessing the deprecated "request.routeSchema" property. Use "request.routeOptions.schema" instead. Property "req.routeSchema" will be removed in `fastify@5`.')

warning.create('FastifyDeprecation', 'FSTDEP016', 'You are accessing the deprecated "request.routerPath" property. Use "request.routeOptions.config.url" instead. Property "req.routerPath" will be removed in `fastify@5`.')
warning.create('FastifyDeprecation', 'FSTDEP016', 'You are accessing the deprecated "request.routeConfig" property. Use "request.routeOptions.config" instead. Property "req.routeConfig" will be removed in `fastify@5`.')

warning.create('FastifyDeprecation', 'FSTDEP017', 'You are accessing the deprecated "request.routerMethod" property. Use "request.routeOptions.config.method" instead. Property "req.routerMethod" will be removed in `fastify@5`.')
warning.create('FastifyDeprecation', 'FSTDEP017', 'You are accessing the deprecated "request.routerPath" property. Use "request.routeOptions.config.url" instead. Property "req.routerPath" will be removed in `fastify@5`.')

warning.create('FastifyDeprecation', 'FSTDEP018', 'You are accessing the deprecated "request.routerMethod" property. Use "request.routeOptions.config.method" instead. Property "req.routerMethod" will be removed in `fastify@5`.')
module.exports = warning
45 changes: 45 additions & 0 deletions test/default-route.test.js
Expand Up @@ -3,6 +3,51 @@
const t = require('tap')
const test = t.test
const Fastify = require('..')
const warning = require('../lib/warnings')

// Silence the standard warning logs. We will test the messages explicitly.
process.removeAllListeners('warning')

test('setDefaultRoute should emit a deprecation warning', t => {
t.plan(2)

const fastify = Fastify()
const defaultRoute = (req, res) => {
res.end('hello from defaultRoute')
}

process.on('warning', onWarning)
function onWarning (warning) {
t.equal(warning.name, 'FastifyDeprecation')
t.equal(warning.code, 'FSTDEP014')
}

t.teardown(() => {
process.removeListener('warning', onWarning)
warning.emitted.set('FSTDEP014', false)
})

fastify.setDefaultRoute(defaultRoute)
})

test('getDefaultRoute should emit a deprecation warning', t => {
t.plan(2)

const fastify = Fastify()

process.on('warning', onWarning)
function onWarning (warning) {
t.equal(warning.name, 'FastifyDeprecation')
t.equal(warning.code, 'FSTDEP014')
}

t.teardown(() => {
process.removeListener('warning', onWarning)
warning.emitted.set('FSTDEP014', false)
})

fastify.getDefaultRoute()
})

test('should fail if defaultRoute is not a function', t => {
t.plan(1)
Expand Down
15 changes: 15 additions & 0 deletions test/types/logger.test-d.ts
Expand Up @@ -123,6 +123,21 @@ const serverAutoInferredFileOption = fastify({

expectType<FastifyBaseLogger>(serverAutoInferredFileOption.log)

const serverAutoInferredSerializerResponseObjectOption = fastify({
logger: {
serializers: {
res (ServerResponse) {
expectType<FastifyReply>(ServerResponse)
return {
status: '200'
}
}
}
}
})

expectType<FastifyBaseLogger>(serverAutoInferredSerializerResponseObjectOption.log)

const serverAutoInferredSerializerObjectOption = fastify({
logger: {
serializers: {
Expand Down
2 changes: 1 addition & 1 deletion types/logger.d.ts
Expand Up @@ -60,7 +60,7 @@ export interface FastifyLoggerOptions<
[key: string]: unknown;
};
res?: (res: RawReply) => {
statusCode: string | number;
statusCode?: string | number;
[key: string]: unknown;
};
};
Expand Down

0 comments on commit d869181

Please sign in to comment.