Skip to content

Commit

Permalink
docs: add optional URL param to upgrade guide and route docs (fastify…
Browse files Browse the repository at this point in the history
…#4680)

* Update v4 migration guide and route docs

* Apply suggestions from code review

Thanks, @Fdawgs

Co-authored-by: Frazer Smith <frazer.dev@outlook.com>

---------

Co-authored-by: Frazer Smith <frazer.dev@outlook.com>
  • Loading branch information
mateus4k and Fdawgs committed Apr 19, 2023
1 parent 8315000 commit bc3f957
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
21 changes: 21 additions & 0 deletions docs/Guides/Migration-Guide-V4.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,27 @@ As a result, if you specify an `onRoute` hook in a plugin you should now either:
});
```

### Optional URL parameters

If you've already used any implicitly optional parameters, you'll get a 404
error when trying to access the route. You will now need to declare the
optional parameters explicitly.

For example, if you have the same route for listing and showing a post,
refactor this:
```js
fastify.get('/posts/:id', (request, reply) => {
const { id } = request.params;
});
```

Into this:
```js
fastify.get('/posts/:id?', (request, reply) => {
const { id } = request.params;
});
```

## Non-Breaking Changes

### Deprecation of variadic `.listen()` signature
Expand Down
11 changes: 11 additions & 0 deletions docs/Reference/Routes.md
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,17 @@ fastify.get('/example/at/:hour(^\\d{2})h:minute(^\\d{2})m', function (request, r
In this case as parameter separator it is possible to use whatever character is
not matched by the regular expression.

The last parameter can be made optional if you add a question mark ("?") to the
end of the parameters name.
```js
fastify.get('/example/posts/:id?', function (request, reply) {
const { id } = request.params;
// your code here
})
```
In this case you can request `/example/posts` as well as `/example/posts/1`.
The optional param will be undefined if not specified.

Having a route with multiple parameters may negatively affect performance, so
prefer a single parameter approach whenever possible, especially on routes that
are on the hot path of your application. If you are interested in how we handle
Expand Down

0 comments on commit bc3f957

Please sign in to comment.