Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add optional URL param to upgrade guide and route docs (#4637) #4680

Merged
merged 3 commits into from
Apr 19, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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. Now you will need to declare the
mateus4k marked this conversation as resolved.
Show resolved Hide resolved
optional parameters explicitly:
mateus4k marked this conversation as resolved.
Show resolved Hide resolved

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 ("?") at the
mateus4k marked this conversation as resolved.
Show resolved Hide resolved
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