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
```
2018-03-21 06:15:28 +00:00
Path-parameters are automatically coerced into strings, with the help of (currently internal) Protocol `reitit.impl/IntoString` . It supports strings, numbers, booleans, keywords and objects:
2018-03-21 05:56:29 +00:00
```clj
(r/match-by-name router ::user {:id 1})
; #Match {:template "/api/user/:id"
; :data {:name :user/user}
; :path "/api/user/1"
; :result nil
; :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}
```
2018-06-25 07:33:27 +00:00
To turn a Match into a path, there is `reitit.core/match->path` :
```clj
(-> router
(r/match-by-name ::user {:id 1})
(r/match->path))
; "/api/user/1"
```
It can take an optional map of query-parameters too:
```clj
(-> router
(r/match-by-name ::user {:id 1})
(r/match->path {:iso "möly"}))
; "/api/user/1?iso=m%C3%B6ly"
```