reitit/doc/coercion/data_spec_coercion.md

44 lines
1.5 KiB
Markdown
Raw Normal View History

2017-12-10 15:46:29 +00:00
# Data-spec Coercion
[Data-specs](https://github.com/metosin/spec-tools#data-specs) is alternative, macro-free syntax to define `clojure.spec`s. As a bonus, supports the [runtime transformations via conforming](https://clojure.atlassian.net/browse/CLJ-2116) out-of-the-box.
2017-12-10 15:46:29 +00:00
```clj
(require '[reitit.coercion.spec])
(require '[reitit.coercion :as coercion])
(require '[reitit.core :as r])
(def router
(r/router
["/:company/users/:user-id" {:name ::user-view
:coercion reitit.coercion.spec/coercion
:parameters {:path {:company string?
:user-id int?}}}]
{:compile coercion/compile-request-coercers}))
2017-12-10 19:48:06 +00:00
(defn match-by-path-and-coerce! [path]
2017-12-10 15:46:29 +00:00
(if-let [match (r/match-by-path router path)]
(assoc match :parameters (coercion/coerce! match))))
```
Successful coercion:
```clj
2017-12-10 19:48:06 +00:00
(match-by-path-and-coerce! "/metosin/users/123")
2017-12-10 15:46:29 +00:00
; #Match{:template "/:company/users/:user-id",
; :data {:name :user/user-view,
; :coercion <<:spec>>
2017-12-10 15:46:29 +00:00
; :parameters {:path {:company string?,
; :user-id int?}}},
; :result {:path #object[reitit.coercion$request_coercer$]},
2018-02-01 14:23:44 +00:00
; :path-params {:company "metosin", :user-id "123"},
2017-12-10 15:46:29 +00:00
; :parameters {:path {:company "metosin", :user-id 123}}
; :path "/metosin/users/123"}
```
Failing coercion:
```clj
2017-12-10 19:48:06 +00:00
(match-by-path-and-coerce! "/metosin/users/ikitommi")
2017-12-10 15:46:29 +00:00
; => ExceptionInfo Request coercion failed...
```