-
-
Notifications
You must be signed in to change notification settings - Fork 37
Description
The typed URL builder will replace the existing router.makeURL and router.makeSignedURL methods in favor of a type-safe API. Additionally, it will be possible to narrow down the route search by the HTTP method.
For example, when calling response.redirect().toRoute(), the typed suggestions should be limited to GET routes only.
Typed URL builder
The URL builder will be exposed as a container service via the @adonisjs/core/services/url_builder path, or one could access it via the router.urlBuilder property.
Creating a URL for a route
The URL can be created for a route using the urlFor method. It will accept the route name or pattern as the first argument, followed by route params and builder options.
import { urlFor } from '@adonisjs/core/services/url_builder'
urlFor('posts.show', [id]) // /posts/1
urlFor('posts.show', { id: 1 }) // /posts/1Creating a URL for a route and a specific HTTP method
You can narrow down the route suggestions to a particular HTTP method using the urlFor.post, urlFor.get, urlFor.put methods, and so on.
import { urlFor } from '@adonisjs/core/services/url_builder'
urlFor.get('posts.show', [id]) // { method: 'GET', url: '/posts/1' }
urlFor.put('posts.edit', [1]) // { method: 'PUT', url: '/posts/1' }Finding routes within a specific domain
Contrary to the existing behavior of the router.makeUrl method, the urlFor method will search for a given route across all the domains. In case there is a duplicate route among two or more domains, you will get suggestions with <domain>@<route-name>.
router.get('posts/:id', [PostsController, 'show'])
router.group(() => {
router.get('posts/:id', [PostsController, 'show'])
}).domain('admin.myapp.com')For the above routes, you will receive the following suggestions.
urlFor('/posts/:id', [1])
urlFor('admin.myapp.com@/posts/:id', [1])The domain prefix routes will only appear if the same pattern is duplicated at the root level or within another domain route.
Signed URLs
You can create signed URLs using the signedUrlFor method. The rest of the API is same as the urlFor method.
Generate routes types
In order to provide a type-safe API, we have to create a type definition file containing all the registered routes. We will do it automatically every time the AdonisJS application starts (or restarts) in development and the output types will be written to the .adonisjs/backend/routes.d.ts file.
Metadata
Metadata
Assignees
Labels
Type
Projects
Status