2017-12-10 16:08:00 +00:00
|
|
|
# Name-based (reverse) Routing
|
2017-10-29 07:29:06 +00:00
|
|
|
|
2017-10-30 06:46:20 +00:00
|
|
|
All routes which have `:name` route data defined, can also be matched by name.
|
|
|
|
|
|
|
|
|
|
Given a router:
|
|
|
|
|
|
|
|
|
|
```clj
|
|
|
|
|
(require '[reitit.core :as r])
|
|
|
|
|
|
|
|
|
|
(def router
|
|
|
|
|
(r/router
|
2018-02-11 17:15:25 +00:00
|
|
|
["/api"
|
|
|
|
|
["/ping" ::ping]
|
|
|
|
|
["/user/:id" ::user]]))
|
2017-10-30 06:46:20 +00:00
|
|
|
```
|
2017-10-29 07:29:06 +00:00
|
|
|
|
|
|
|
|
Listing all route names:
|
|
|
|
|
|
|
|
|
|
```clj
|
|
|
|
|
(r/route-names router)
|
|
|
|
|
; [:user/ping :user/user]
|
|
|
|
|
```
|
|
|
|
|
|
2017-10-30 06:46:20 +00:00
|
|
|
No match returns `nil`:
|
|
|
|
|
|
|
|
|
|
```clj
|
|
|
|
|
(r/match-by-name router ::kikka)
|
|
|
|
|
nil
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
Matching a route:
|
|
|
|
|
|
|
|
|
|
```clj
|
|
|
|
|
(r/match-by-name router ::ping)
|
|
|
|
|
; #Match{:template "/api/ping"
|
2017-11-18 10:47:16 +00:00
|
|
|
; :data {:name :user/ping}
|
2017-10-30 06:46:20 +00:00
|
|
|
; :result nil
|
2018-02-01 14:23:44 +00:00
|
|
|
; :path-params {}
|
2017-10-30 06:46:20 +00:00
|
|
|
; :path "/api/ping"}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
If not all path-parameters are set, a `PartialMatch` is returned:
|
2017-10-29 07:29:06 +00:00
|
|
|
|
|
|
|
|
```clj
|
|
|
|
|
(r/match-by-name router ::user)
|
|
|
|
|
; #PartialMatch{:template "/api/user/:id",
|
2017-11-18 10:47:16 +00:00
|
|
|
; :data {:name :user/user},
|
2017-10-29 07:29:06 +00:00
|
|
|
; :result nil,
|
2018-02-01 14:23:44 +00:00
|
|
|
; :path-params nil,
|
2017-10-29 07:29:06 +00:00
|
|
|
; :required #{:id}}
|
|
|
|
|
|
|
|
|
|
(r/partial-match? (r/match-by-name router ::user))
|
|
|
|
|
; true
|
|
|
|
|
```
|
|
|
|
|
|
2017-10-30 06:46:20 +00:00
|
|
|
With provided path-parameters:
|
2017-10-29 07:29:06 +00:00
|
|
|
|
|
|
|
|
```clj
|
|
|
|
|
(r/match-by-name router ::user {:id "1"})
|
|
|
|
|
; #Match{:template "/api/user/:id"
|
2017-11-18 10:47:16 +00:00
|
|
|
; :data {:name :user/user}
|
2017-10-29 07:29:06 +00:00
|
|
|
; :path "/api/user/1"
|
|
|
|
|
; :result nil
|
2018-02-01 14:23:44 +00:00
|
|
|
; :path-params {:id "1"}}
|
2017-10-29 07:29:06 +00:00
|
|
|
```
|
|
|
|
|
|
|
|
|
|
There is also a exception throwing version:
|
|
|
|
|
|
|
|
|
|
```clj
|
|
|
|
|
(r/match-by-name! router ::user)
|
|
|
|
|
; ExceptionInfo missing path-params for route /api/user/:id: #{:id}
|
|
|
|
|
```
|