reitit/coercion/coercion.html
2018-02-19 05:45:45 +00:00

760 lines
28 KiB
HTML

<!DOCTYPE HTML>
<html lang="" >
<head>
<meta charset="UTF-8">
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Coercion Explained · GitBook</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="description" content="">
<meta name="generator" content="GitBook 3.2.3">
<link rel="stylesheet" href="../gitbook/style.css">
<link rel="stylesheet" href="../gitbook/gitbook-plugin-highlight/website.css">
<link rel="stylesheet" href="../gitbook/gitbook-plugin-search/search.css">
<link rel="stylesheet" href="../gitbook/gitbook-plugin-fontsettings/website.css">
<meta name="HandheldFriendly" content="true"/>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="apple-touch-icon-precomposed" sizes="152x152" href="../gitbook/images/apple-touch-icon-precomposed-152.png">
<link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">
<link rel="next" href="schema_coercion.html" />
<link rel="prev" href="./" />
</head>
<body>
<div class="book">
<div class="book-summary">
<div id="book-search-input" role="search">
<input type="text" placeholder="Type to search" />
</div>
<nav role="navigation">
<ul class="summary">
<li class="chapter " data-level="1.1" data-path="../">
<a href="../">
Introduction
</a>
</li>
<li class="chapter " data-level="1.2" data-path="../basics/">
<a href="../basics/">
Basics
</a>
<ul class="articles">
<li class="chapter " data-level="1.2.1" data-path="../basics/route_syntax.html">
<a href="../basics/route_syntax.html">
Route Syntax
</a>
</li>
<li class="chapter " data-level="1.2.2" data-path="../basics/router.html">
<a href="../basics/router.html">
Router
</a>
</li>
<li class="chapter " data-level="1.2.3" data-path="../basics/path_based_routing.html">
<a href="../basics/path_based_routing.html">
Path-based Routing
</a>
</li>
<li class="chapter " data-level="1.2.4" data-path="../basics/name_based_routing.html">
<a href="../basics/name_based_routing.html">
Name-based Routing
</a>
</li>
<li class="chapter " data-level="1.2.5" data-path="../basics/route_data.html">
<a href="../basics/route_data.html">
Route Data
</a>
</li>
<li class="chapter " data-level="1.2.6" data-path="../basics/route_data_validation.html">
<a href="../basics/route_data_validation.html">
Route Data Validation
</a>
</li>
<li class="chapter " data-level="1.2.7" data-path="../basics/route_conflicts.html">
<a href="../basics/route_conflicts.html">
Route Conflicts
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="1.3" data-path="./">
<a href="./">
Coercion
</a>
<ul class="articles">
<li class="chapter active" data-level="1.3.1" data-path="coercion.html">
<a href="coercion.html">
Coercion Explained
</a>
</li>
<li class="chapter " data-level="1.3.2" data-path="schema_coercion.html">
<a href="schema_coercion.html">
Plumatic Schema
</a>
</li>
<li class="chapter " data-level="1.3.3" data-path="clojure_spec_coercion.html">
<a href="clojure_spec_coercion.html">
Clojure.spec
</a>
</li>
<li class="chapter " data-level="1.3.4" data-path="data_spec_coercion.html">
<a href="data_spec_coercion.html">
Data-specs
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="1.4" data-path="../advanced/">
<a href="../advanced/">
Advanced
</a>
<ul class="articles">
<li class="chapter " data-level="1.4.1" data-path="../advanced/configuring_routers.html">
<a href="../advanced/configuring_routers.html">
Configuring Routers
</a>
</li>
<li class="chapter " data-level="1.4.2" data-path="../advanced/different_routers.html">
<a href="../advanced/different_routers.html">
Different Routers
</a>
</li>
<li class="chapter " data-level="1.4.3" data-path="../advanced/route_validation.html">
<a href="../advanced/route_validation.html">
Route Validation
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="1.5" data-path="../ring/">
<a href="../ring/">
Ring
</a>
<ul class="articles">
<li class="chapter " data-level="1.5.1" data-path="../ring/ring.html">
<a href="../ring/ring.html">
Ring-router
</a>
</li>
<li class="chapter " data-level="1.5.2" data-path="../ring/dynamic_extensions.html">
<a href="../ring/dynamic_extensions.html">
Dynamic Extensions
</a>
</li>
<li class="chapter " data-level="1.5.3" data-path="../ring/data_driven_middleware.html">
<a href="../ring/data_driven_middleware.html">
Data-driven Middleware
</a>
</li>
<li class="chapter " data-level="1.5.4" data-path="../ring/coercion.html">
<a href="../ring/coercion.html">
Pluggable Coercion
</a>
</li>
<li class="chapter " data-level="1.5.5" data-path="../ring/route_data_validation.html">
<a href="../ring/route_data_validation.html">
Route Data Validation
</a>
</li>
<li class="chapter " data-level="1.5.6" data-path="../ring/compiling_middleware.html">
<a href="../ring/compiling_middleware.html">
Compiling Middleware
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="1.6" data-path="../performance.html">
<a href="../performance.html">
Performance
</a>
</li>
<li class="chapter " data-level="1.7" data-path="../interceptors.html">
<a href="../interceptors.html">
Interceptors (WIP)
</a>
</li>
<li class="chapter " data-level="1.8" data-path="../openapi.html">
<a href="../openapi.html">
Swagger & Openapi (WIP)
</a>
</li>
<li class="chapter " data-level="1.9" data-path="../faq.html">
<a href="../faq.html">
FAQ
</a>
</li>
<li class="divider"></li>
<li>
<a href="https://www.gitbook.com" target="blank" class="gitbook-link">
Published with GitBook
</a>
</li>
</ul>
</nav>
</div>
<div class="book-body">
<div class="body-inner">
<div class="book-header" role="navigation">
<!-- Title -->
<h1>
<i class="fa fa-circle-o-notch fa-spin"></i>
<a href=".." >Coercion Explained</a>
</h1>
</div>
<div class="page-wrapper" tabindex="-1" role="main">
<div class="page-inner">
<div id="book-search-results">
<div class="search-noresults">
<section class="normal markdown-section">
<h1 id="coercion-explained">Coercion Explained</h1>
<p>Coercion is a process of transforming parameters (and responses) from one format into another. Reitit separates routing and coercion into two separate steps.</p>
<p>By default, all wildcard and catch-all parameters are parsed into strings:</p>
<pre><code class="lang-clj">(<span class="hljs-name">require</span> &apos;[reitit.core <span class="hljs-symbol">:as</span> r])
(<span class="hljs-name"><span class="hljs-builtin-name">def</span></span> router
(<span class="hljs-name">r/router</span>
[<span class="hljs-string">&quot;/:company/users/:user-id&quot;</span> <span class="hljs-symbol">::user-view</span>]))
</code></pre>
<p>Match with the parsed <code>:path-params</code> as strings:</p>
<pre><code class="lang-clj">(<span class="hljs-name">r/match-by-path</span> r <span class="hljs-string">&quot;/metosin/users/123&quot;</span>)
<span class="hljs-comment">; #Match{:template &quot;/:company/users/:user-id&quot;,</span>
<span class="hljs-comment">; :data {:name :user/user-view},</span>
<span class="hljs-comment">; :result nil,</span>
<span class="hljs-comment">; :path-params {:company &quot;metosin&quot;, :user-id &quot;123&quot;},</span>
<span class="hljs-comment">; :path &quot;/metosin/users/123&quot;}</span>
</code></pre>
<p>To enable parameter coercion, the following things need to be done:</p>
<ol>
<li>Define a <code>Coercion</code> for the routes</li>
<li>Define types for the parameters</li>
<li>Compile coercers for the types</li>
<li>Apply the coercion</li>
</ol>
<h2 id="define-coercion">Define Coercion</h2>
<p><code>reitit.coercion/Coercion</code> is a protocol defining how types are defined, coerced and inventoried.</p>
<p>Reitit ships with the following coercion modules:</p>
<ul>
<li><code>reitit.coercion.schema/coercion</code> for <a href="https://github.com/plumatic/schema" target="_blank">plumatic schema</a></li>
<li><code>reitit.coercion.spec/coercion</code> for both <a href="https://clojure.org/about/spec" target="_blank">clojure.spec</a> and <a href="https://github.com/metosin/spec-tools#data-specs" target="_blank">data-specs</a></li>
</ul>
<p>Coercion can be attached to route data under <code>:coercion</code> key. There can be multiple <code>Coercion</code> implementations within a single router, normal <a href="../basics/route_data.html#nested-route-data">scoping rules</a> apply.</p>
<h2 id="defining-parameters">Defining parameters</h2>
<p>Route parameters can be defined via route data <code>:parameters</code>. It has keys for different type of parameters: <code>:query</code>, <code>:body</code>, <code>:form</code>, <code>:header</code> and <code>:path</code>. Syntax for the actual parameters depends on the <code>Coercion</code> implementation.</p>
<p>Example with Schema path-parameters:</p>
<pre><code class="lang-clj">(<span class="hljs-name">require</span> &apos;[reitit.coercion.schema])
(<span class="hljs-name">require</span> &apos;[schema.core <span class="hljs-symbol">:as</span> s])
(<span class="hljs-name"><span class="hljs-builtin-name">def</span></span> router
(<span class="hljs-name">r/router</span>
[<span class="hljs-string">&quot;/:company/users/:user-id&quot;</span> {<span class="hljs-symbol">:name</span> <span class="hljs-symbol">::user-view</span>
<span class="hljs-symbol">:coercion</span> reitit.coercion.schema/coercion
<span class="hljs-symbol">:parameters</span> {<span class="hljs-symbol">:path</span> {<span class="hljs-symbol">:company</span> s/Str
<span class="hljs-symbol">:user-id</span> s/Int}}}]))
</code></pre>
<p>A Match:</p>
<pre><code class="lang-clj">(<span class="hljs-name">r/match-by-path</span> r <span class="hljs-string">&quot;/metosin/users/123&quot;</span>)
<span class="hljs-comment">; #Match{:template &quot;/:company/users/:user-id&quot;,</span>
<span class="hljs-comment">; :data {:name :user/user-view,</span>
<span class="hljs-comment">; :coercion &lt;&lt;:schema&gt;&gt;</span>
<span class="hljs-comment">; :parameters {:path {:company java.lang.String,</span>
<span class="hljs-comment">; :user-id Int}}},</span>
<span class="hljs-comment">; :result nil,</span>
<span class="hljs-comment">; :path-params {:company &quot;metosin&quot;, :user-id &quot;123&quot;},</span>
<span class="hljs-comment">; :path &quot;/metosin/users/123&quot;}</span>
</code></pre>
<p>Coercion was not applied. Why? In Reitit, routing and coercion are separate processes and we have done just the routing part. We need to apply coercion after the successful routing.</p>
<p>But now we should have enough data on the match to apply the coercion.</p>
<h2 id="compiling-coercers">Compiling coercers</h2>
<p>Before the actual coercion, we <del>should</del> need to compile the coercers against the route data. Compiled coercers yield much better performance and the manual step of adding a coercion compiler makes things explicit and non-magical.</p>
<p>Compiling can be done via a Middleware, Interceptor or a Router. We apply it now at router-level, effecting all routes (with <code>:parameters</code> and <code>:coercion</code> defined).</p>
<p>There is a helper function <code>reitit.coercion/compile-request-coercers</code> just for this:</p>
<pre><code class="lang-clj">(<span class="hljs-name">require</span> &apos;[reitit.coercion <span class="hljs-symbol">:as</span> coercion])
(<span class="hljs-name">require</span> &apos;[reitit.coercion.schema])
(<span class="hljs-name">require</span> &apos;[schema.core <span class="hljs-symbol">:as</span> s])
(<span class="hljs-name"><span class="hljs-builtin-name">def</span></span> router
(<span class="hljs-name">r/router</span>
[<span class="hljs-string">&quot;/:company/users/:user-id&quot;</span> {<span class="hljs-symbol">:name</span> <span class="hljs-symbol">::user-view</span>
<span class="hljs-symbol">:coercion</span> reitit.coercion.schema/coercion
<span class="hljs-symbol">:parameters</span> {<span class="hljs-symbol">:path</span> {<span class="hljs-symbol">:company</span> s/Str
<span class="hljs-symbol">:user-id</span> s/Int}}}]
{<span class="hljs-symbol">:compile</span> coercion/compile-request-coercers}))
</code></pre>
<p>Routing again:</p>
<pre><code class="lang-clj">(<span class="hljs-name">r/match-by-path</span> r <span class="hljs-string">&quot;/metosin/users/123&quot;</span>)
<span class="hljs-comment">; #Match{:template &quot;/:company/users/:user-id&quot;,</span>
<span class="hljs-comment">; :data {:name :user/user-view,</span>
<span class="hljs-comment">; :coercion &lt;&lt;:schema&gt;&gt;</span>
<span class="hljs-comment">; :parameters {:path {:company java.lang.String,</span>
<span class="hljs-comment">; :user-id Int}}},</span>
<span class="hljs-comment">; :result {:path #object[reitit.coercion$request_coercer$]},</span>
<span class="hljs-comment">; :path-params {:company &quot;metosin&quot;, :user-id &quot;123&quot;},</span>
<span class="hljs-comment">; :path &quot;/metosin/users/123&quot;}</span>
</code></pre>
<p>The compiler added a <code>:result</code> key into the match (done just once, at router creation time), which holds the compiled coercers. We are almost done.</p>
<h2 id="applying-coercion">Applying coercion</h2>
<p>We can use a helper function <code>reitit.coercion/coerce!</code> to do the actual coercion, based on a <code>Match</code>:</p>
<pre><code class="lang-clj">(<span class="hljs-name">coercion/coerce!</span>
(<span class="hljs-name">r/match-by-path</span> router <span class="hljs-string">&quot;/metosin/users/123&quot;</span>))
<span class="hljs-comment">; {:path {:company &quot;metosin&quot;, :user-id 123}}</span>
</code></pre>
<p>We get the coerced paremeters back. If a coercion fails, a typed (<code>:reitit.coercion/request-coercion</code>) ExceptionInfo is thrown, with data about the actual error:</p>
<pre><code class="lang-clj">(<span class="hljs-name">coercion/coerce!</span>
(<span class="hljs-name">r/match-by-path</span> router <span class="hljs-string">&quot;/metosin/users/ikitommi&quot;</span>))
<span class="hljs-comment">; =&gt; ExceptionInfo Request coercion failed:</span>
<span class="hljs-comment">; #CoercionError{:schema {:company java.lang.String, :user-id Int, Any Any},</span>
<span class="hljs-comment">; :errors {:user-id (not (integer? &quot;ikitommi&quot;))}}</span>
<span class="hljs-comment">; clojure.core/ex-info (core.clj:4739)</span>
</code></pre>
<h2 id="full-example">Full example</h2>
<p>Here&apos;s an full example for doing routing and coercion with Reitit and Schema:</p>
<pre><code class="lang-clj">(<span class="hljs-name">require</span> &apos;[reitit.coercion.schema])
(<span class="hljs-name">require</span> &apos;[reitit.coercion <span class="hljs-symbol">:as</span> coercion])
(<span class="hljs-name">require</span> &apos;[reitit.core <span class="hljs-symbol">:as</span> r])
(<span class="hljs-name">require</span> &apos;[schema.core <span class="hljs-symbol">:as</span> s])
(<span class="hljs-name"><span class="hljs-builtin-name">def</span></span> router
(<span class="hljs-name">r/router</span>
[<span class="hljs-string">&quot;/:company/users/:user-id&quot;</span> {<span class="hljs-symbol">:name</span> <span class="hljs-symbol">::user-view</span>
<span class="hljs-symbol">:coercion</span> reitit.coercion.schema/coercion
<span class="hljs-symbol">:parameters</span> {<span class="hljs-symbol">:path</span> {<span class="hljs-symbol">:company</span> s/Str
<span class="hljs-symbol">:user-id</span> s/Int}}}]
{<span class="hljs-symbol">:compile</span> coercion/compile-request-coercers}))
(<span class="hljs-name"><span class="hljs-builtin-name">defn</span></span> match-by-path-and-coerce! [path]
(<span class="hljs-name"><span class="hljs-builtin-name">if-let</span></span> [match (<span class="hljs-name">r/match-by-path</span> router path)]
(<span class="hljs-name"><span class="hljs-builtin-name">assoc</span></span> match <span class="hljs-symbol">:parameters</span> (<span class="hljs-name">coercion/coerce!</span> match))))
(<span class="hljs-name">match-by-path-and-coerce!</span> <span class="hljs-string">&quot;/metosin/users/123&quot;</span>)
<span class="hljs-comment">; #Match{:template &quot;/:company/users/:user-id&quot;,</span>
<span class="hljs-comment">; :data {:name :user/user-view,</span>
<span class="hljs-comment">; :coercion &lt;&lt;:schema&gt;&gt;</span>
<span class="hljs-comment">; :parameters {:path {:company java.lang.String,</span>
<span class="hljs-comment">; :user-id Int}}},</span>
<span class="hljs-comment">; :result {:path #object[reitit.coercion$request_coercer$]},</span>
<span class="hljs-comment">; :path-params {:company &quot;metosin&quot;, :user-id &quot;123&quot;},</span>
<span class="hljs-comment">; :parameters {:path {:company &quot;metosin&quot;, :user-id 123}}</span>
<span class="hljs-comment">; :path &quot;/metosin/users/123&quot;}</span>
(<span class="hljs-name">match-by-path-and-coerce!</span> <span class="hljs-string">&quot;/metosin/users/ikitommi&quot;</span>)
<span class="hljs-comment">; =&gt; ExceptionInfo Request coercion failed...</span>
</code></pre>
<h2 id="ring-coercion">Ring Coercion</h2>
<p>For a full-blown http-coercion, see the <a href="../ring/coercion.html">ring coercion</a>.</p>
</section>
</div>
<div class="search-results">
<div class="has-results">
<h1 class="search-results-title"><span class='search-results-count'></span> results matching "<span class='search-query'></span>"</h1>
<ul class="search-results-list"></ul>
</div>
<div class="no-results">
<h1 class="search-results-title">No results matching "<span class='search-query'></span>"</h1>
</div>
</div>
</div>
</div>
</div>
</div>
<a href="./" class="navigation navigation-prev " aria-label="Previous page: Coercion">
<i class="fa fa-angle-left"></i>
</a>
<a href="schema_coercion.html" class="navigation navigation-next " aria-label="Next page: Plumatic Schema">
<i class="fa fa-angle-right"></i>
</a>
</div>
<script>
var gitbook = gitbook || [];
gitbook.push(function() {
gitbook.page.hasChanged({"page":{"title":"Coercion Explained","level":"1.3.1","depth":2,"next":{"title":"Plumatic Schema","level":"1.3.2","depth":2,"path":"coercion/schema_coercion.md","ref":"coercion/schema_coercion.md","articles":[]},"previous":{"title":"Coercion","level":"1.3","depth":1,"path":"coercion/README.md","ref":"coercion/README.md","articles":[{"title":"Coercion Explained","level":"1.3.1","depth":2,"path":"coercion/coercion.md","ref":"coercion/coercion.md","articles":[]},{"title":"Plumatic Schema","level":"1.3.2","depth":2,"path":"coercion/schema_coercion.md","ref":"coercion/schema_coercion.md","articles":[]},{"title":"Clojure.spec","level":"1.3.3","depth":2,"path":"coercion/clojure_spec_coercion.md","ref":"coercion/clojure_spec_coercion.md","articles":[]},{"title":"Data-specs","level":"1.3.4","depth":2,"path":"coercion/data_spec_coercion.md","ref":"coercion/data_spec_coercion.md","articles":[]}]},"dir":"ltr"},"config":{"plugins":["editlink","github","highlight"],"root":"doc","styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"pluginsConfig":{"editlink":{"label":"Edit This Page","multilingual":false,"base":"https://github.com/metosin/reitit/tree/master/doc"},"github":{"url":"https://github.com/metosin/reitit"},"highlight":{},"search":{},"lunr":{"maxIndexSize":1000000,"ignoreSpecialCharacters":false},"sharing":{"facebook":true,"twitter":true,"google":false,"weibo":false,"instapaper":false,"vk":false,"all":["facebook","google","twitter","weibo","instapaper"]},"fontsettings":{"theme":"white","family":"sans","size":2},"theme-default":{"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"showLevel":false}},"theme":"default","pdf":{"pageNumbers":true,"fontSize":12,"fontFamily":"Arial","paperSize":"a4","chapterMark":"pagebreak","pageBreaksBefore":"/","margin":{"right":62,"left":62,"top":56,"bottom":56}},"structure":{"langs":"LANGS.md","readme":"README.md","glossary":"GLOSSARY.md","summary":"SUMMARY.md"},"variables":{},"gitbook":"*"},"file":{"path":"coercion/coercion.md","mtime":"2018-02-19T05:44:55.035Z","type":"markdown"},"gitbook":{"version":"3.2.3","time":"2018-02-19T05:45:40.099Z"},"basePath":"..","book":{"language":""}});
});
</script>
</div>
<script src="../gitbook/gitbook.js"></script>
<script src="../gitbook/theme.js"></script>
<script src="../gitbook/gitbook-plugin-editlink/plugin.js"></script>
<script src="../gitbook/gitbook-plugin-github/plugin.js"></script>
<script src="../gitbook/gitbook-plugin-search/search-engine.js"></script>
<script src="../gitbook/gitbook-plugin-search/search.js"></script>
<script src="../gitbook/gitbook-plugin-lunr/lunr.min.js"></script>
<script src="../gitbook/gitbook-plugin-lunr/search-lunr.js"></script>
<script src="../gitbook/gitbook-plugin-sharing/buttons.js"></script>
<script src="../gitbook/gitbook-plugin-fontsettings/fontsettings.js"></script>
</body>
</html>