This repository has been archived by the owner on Jun 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
ScalaValidationExtensions.html
623 lines (360 loc) · 34.4 KB
/
ScalaValidationExtensions.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
<!DOCTYPE HTML>
<html lang="" >
<head>
<title>Extensions: Supporting new types · GitBook</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="description" content="">
<meta name="generator" content="GitBook 3.0.2">
<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="ScalaValidationCookbook.html" />
<link rel="prev" href="ScalaJsValidation.html" />
</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" >
<span>
Features
</span>
<ul class="articles">
<li class="chapter " data-level="1.2.1" data-path="ScalaValidationRule.html">
<a href="ScalaValidationRule.html">
Validating and transforming data
</a>
</li>
<li class="chapter " data-level="1.2.2" data-path="ScalaValidationRuleCombinators.html">
<a href="ScalaValidationRuleCombinators.html">
Combining Rules
</a>
</li>
<li class="chapter " data-level="1.2.3" data-path="ScalaValidationWrite.html">
<a href="ScalaValidationWrite.html">
Serializing data with Write
</a>
</li>
<li class="chapter " data-level="1.2.4" data-path="ScalaValidationWriteCombinators.html">
<a href="ScalaValidationWriteCombinators.html">
Combining Writes
</a>
</li>
<li class="chapter " data-level="1.2.5" data-path="ScalaValidationMacros.html">
<a href="ScalaValidationMacros.html">
Validation Inception
</a>
</li>
<li class="chapter " data-level="1.2.6" data-path="ScalaJsValidation.html">
<a href="ScalaJsValidation.html">
Exporting Validations to Javascript using Scala.js
</a>
</li>
<li class="chapter active" data-level="1.2.7" data-path="ScalaValidationExtensions.html">
<a href="ScalaValidationExtensions.html">
Extensions: Supporting new types
</a>
</li>
<li class="chapter " data-level="1.2.8" data-path="ScalaValidationCookbook.html">
<a href="ScalaValidationCookbook.html">
Cookbook
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="1.3" >
<span>
Migration
</span>
<ul class="articles">
<li class="chapter " data-level="1.3.1" data-path="V2MigrationGuide.html">
<a href="V2MigrationGuide.html">
v2.0 Migration guide
</a>
</li>
<li class="chapter " data-level="1.3.2" data-path="ScalaValidationMigrationForm.html">
<a href="ScalaValidationMigrationForm.html">
Play's Form API migration
</a>
</li>
<li class="chapter " data-level="1.3.3" data-path="ScalaValidationMigrationJson.html">
<a href="ScalaValidationMigrationJson.html">
Play's Json API migration
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="1.4" data-path="ReleaseNotes.html">
<a href="ReleaseNotes.html">
Release notes
</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="." >Extensions: Supporting new types</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="extensions-supporting-new-types">Extensions: Supporting new types</h1>
<p>The validation API is designed to be easily extensible. Supporting new types is just a matter of providing the appropriate set of Rules and Writes.</p>
<p>In this documentation, we'll study the implementation of the Json support. All extensions are to be defined in a similar fashion. The total amount of code needed is rather small, but there're best practices you need to follow.</p>
<h2 id="rules">Rules</h2>
<p>The first step is to define what we call primitive rules. Primitive rules is a set of rules on which you could build any complex validation.</p>
<p>The base of all Rules is the capacity to extract a subset of some input data.</p>
<p>For the type <code>JsValue</code>, we need to be able to extract a <code>JsValue</code> at a given <code>Path</code>:</p>
<pre><code class="lang-scala">scala> <span class="hljs-keyword">import</span> jto.validation._
<span class="hljs-keyword">import</span> jto.validation._
scala> <span class="hljs-keyword">import</span> play.api.libs.json.{<span class="hljs-type">KeyPathNode</span> => <span class="hljs-type">JSKeyPathNode</span>, <span class="hljs-type">IdxPathNode</span> => <span class="hljs-type">JIdxPathNode</span>, _}
<span class="hljs-keyword">import</span> play.api.libs.json.{<span class="hljs-type">KeyPathNode</span>=><span class="hljs-type">JSKeyPathNode</span>, <span class="hljs-type">IdxPathNode</span>=><span class="hljs-type">JIdxPathNode</span>, _}
scala> <span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">Ex1</span> </span>{
|
| <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">pathToJsPath</span></span>(p: <span class="hljs-type">Path</span>) =
| play.api.libs.json.<span class="hljs-type">JsPath</span>(p.path.map{
| <span class="hljs-keyword">case</span> <span class="hljs-type">KeyPathNode</span>(key) => <span class="hljs-type">JSKeyPathNode</span>(key)
| <span class="hljs-keyword">case</span> <span class="hljs-type">IdxPathNode</span>(i) => <span class="hljs-type">JIdxPathNode</span>(i)
| })
|
| <span class="hljs-keyword">implicit</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">pickInJson</span></span>(p: <span class="hljs-type">Path</span>): <span class="hljs-type">Rule</span>[<span class="hljs-type">JsValue</span>, <span class="hljs-type">JsValue</span>] =
| <span class="hljs-type">Rule</span>[<span class="hljs-type">JsValue</span>, <span class="hljs-type">JsValue</span>] { json =>
| pathToJsPath(p)(json) <span class="hljs-keyword">match</span> {
| <span class="hljs-keyword">case</span> <span class="hljs-type">Nil</span> => <span class="hljs-type">Invalid</span>(<span class="hljs-type">Seq</span>(<span class="hljs-type">Path</span> -> <span class="hljs-type">Seq</span>(<span class="hljs-type">ValidationError</span>(<span class="hljs-string">"error.required"</span>))))
| <span class="hljs-keyword">case</span> js :: _ => <span class="hljs-type">Valid</span>(js)
| }
| }
| }
defined <span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">Ex1</span></span>
</code></pre>
<p>Now we are able to do this:</p>
<pre><code class="lang-scala">scala> {
| <span class="hljs-keyword">import</span> <span class="hljs-type">Ex1</span>._
|
| <span class="hljs-keyword">val</span> js = <span class="hljs-type">Json</span>.obj(
| <span class="hljs-string">"field1"</span> -> <span class="hljs-string">"alpha"</span>,
| <span class="hljs-string">"field2"</span> -> <span class="hljs-number">123</span>L,
| <span class="hljs-string">"field3"</span> -> <span class="hljs-type">Json</span>.obj(
| <span class="hljs-string">"field31"</span> -> <span class="hljs-string">"beta"</span>,
| <span class="hljs-string">"field32"</span>-> <span class="hljs-number">345</span>))
|
| <span class="hljs-keyword">val</span> pick: <span class="hljs-type">Rule</span>[<span class="hljs-type">JsValue</span>, <span class="hljs-type">JsValue</span>] = <span class="hljs-type">From</span>[<span class="hljs-type">JsValue</span>] { __ =>
| (__ \ <span class="hljs-string">"field2"</span>).read[<span class="hljs-type">JsValue</span>]
| }
|
| pick.validate(js)
| }
res0: jto.validation.<span class="hljs-type">VA</span>[play.api.libs.json.<span class="hljs-type">JsValue</span>] = <span class="hljs-type">Valid</span>(<span class="hljs-number">123</span>)
</code></pre>
<p>Which is nice, but is would be much more convenient if we could extract that value as an <code>Int</code>.</p>
<p>One solution is to write the following method:</p>
<pre><code class="lang-scala"><span class="hljs-keyword">implicit</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">pickIntInJson</span></span>[<span class="hljs-type">O</span>](p: <span class="hljs-type">Path</span>): <span class="hljs-type">Rule</span>[<span class="hljs-type">JsValue</span>, <span class="hljs-type">JsValue</span>] = ???
</code></pre>
<p>But we would end up copying 90% of the code we already wrote.
Instead of doing so, we're going to make <code>pickInJson</code> a bit smarter by adding an implicit parameter:</p>
<pre><code class="lang-scala"><span class="hljs-keyword">implicit</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">pickInJson</span></span>[<span class="hljs-type">O</span>](p: <span class="hljs-type">Path</span>)(<span class="hljs-keyword">implicit</span> r: <span class="hljs-type">Rule</span>[<span class="hljs-type">JsValue</span>, <span class="hljs-type">O</span>]): <span class="hljs-type">Rule</span>[<span class="hljs-type">JsValue</span>, <span class="hljs-type">O</span>] =
<span class="hljs-type">Rule</span>[<span class="hljs-type">JsValue</span>, <span class="hljs-type">JsValue</span>] { json =>
pathToJsPath(p)(json) <span class="hljs-keyword">match</span> {
<span class="hljs-keyword">case</span> <span class="hljs-type">Nil</span> => <span class="hljs-type">Invalid</span>(<span class="hljs-type">Seq</span>(<span class="hljs-type">Path</span> -> <span class="hljs-type">Seq</span>(<span class="hljs-type">ValidationError</span>(<span class="hljs-string">"error.required"</span>))))
<span class="hljs-keyword">case</span> js :: _ => <span class="hljs-type">Valid</span>(js)
}
}.andThen(r)
</code></pre>
<p>The now all we have to do is to write a <code>Rule[JsValue, O]</code>, and we automatically get the <code>Path => Rule[JsValue, O]</code> we're interested in. The rest is just a matter of defining all the primitives rules, for example:</p>
<pre><code class="lang-scala">scala> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">jsonAs</span></span>[<span class="hljs-type">T</span>](f: <span class="hljs-type">PartialFunction</span>[<span class="hljs-type">JsValue</span>, <span class="hljs-type">Validated</span>[<span class="hljs-type">Seq</span>[<span class="hljs-type">ValidationError</span>], <span class="hljs-type">T</span>]])(args: <span class="hljs-type">Any</span>*) =
| <span class="hljs-type">Rule</span>.fromMapping[<span class="hljs-type">JsValue</span>, <span class="hljs-type">T</span>](
| f.orElse{ <span class="hljs-keyword">case</span> j => <span class="hljs-type">Invalid</span>(<span class="hljs-type">Seq</span>(<span class="hljs-type">ValidationError</span>(<span class="hljs-string">"validation.invalid"</span>, args: _*)))
| })
jsonAs: [<span class="hljs-type">T</span>](f: <span class="hljs-type">PartialFunction</span>[play.api.libs.json.<span class="hljs-type">JsValue</span>,jto.validation.<span class="hljs-type">Validated</span>[<span class="hljs-type">Seq</span>[jto.validation.<span class="hljs-type">ValidationError</span>],<span class="hljs-type">T</span>]])(args: <span class="hljs-type">Any</span>*)jto.validation.<span class="hljs-type">Rule</span>[play.api.libs.json.<span class="hljs-type">JsValue</span>,<span class="hljs-type">T</span>]
scala> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">stringRule</span> </span>= jsonAs[<span class="hljs-type">String</span>] {
| <span class="hljs-keyword">case</span> <span class="hljs-type">JsString</span>(v) => <span class="hljs-type">Valid</span>(v)
| }(<span class="hljs-string">"String"</span>)
stringRule: jto.validation.<span class="hljs-type">Rule</span>[play.api.libs.json.<span class="hljs-type">JsValue</span>,<span class="hljs-type">String</span>]
scala> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">booleanRule</span> </span>= jsonAs[<span class="hljs-type">Boolean</span>]{
| <span class="hljs-keyword">case</span> <span class="hljs-type">JsBoolean</span>(v) => <span class="hljs-type">Valid</span>(v)
| }(<span class="hljs-string">"Boolean"</span>)
booleanRule: jto.validation.<span class="hljs-type">Rule</span>[play.api.libs.json.<span class="hljs-type">JsValue</span>,<span class="hljs-type">Boolean</span>]
</code></pre>
<p>The types you generally want to support natively are:</p>
<ul>
<li>String</li>
<li>Boolean</li>
<li>Int</li>
<li>Short</li>
<li>Long</li>
<li>Float</li>
<li>Double</li>
<li>java BigDecimal</li>
<li>scala BigDecimal</li>
</ul>
<h2 id="higher-order-rules">Higher order Rules</h2>
<p>Supporting primitives is nice, but not enough. Users are going to deal with <code>Seq</code> and <code>Option</code>. We need to support those types too.</p>
<h3 id="option">Option</h3>
<p>What we want to do is to implement a function that takes a <code>Path => Rule[JsValue, O]</code>, an lift it into a <code>Path => Rule[JsValue, Option[O]]</code> for any type <code>O</code>. The reason we're working on the fully defined <code>Path => Rule[JsValue, O]</code> and not just <code>Rule[JsValue, O]</code> is because a non-existent <code>Path</code> must be validated as a <code>Valid(None)</code>. If we were to use <code>pickInJson</code> on a <code>Rule[JsValue, Option[O]]</code>, we would end up with an <code>Invalid</code> in the case of non-existing <code>Path</code>.</p>
<p>The <code>play.api.data.mapping.DefaultRules[I]</code> traits provides a helper for building the desired method. It's signature is:</p>
<pre><code class="lang-scala"><span class="hljs-keyword">protected</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">opt</span></span>[<span class="hljs-type">J</span>, <span class="hljs-type">O</span>](r: => <span class="hljs-type">Rule</span>[<span class="hljs-type">J</span>, <span class="hljs-type">O</span>], noneValues: <span class="hljs-type">Rule</span>[<span class="hljs-type">I</span>, <span class="hljs-type">I</span>]*)(<span class="hljs-keyword">implicit</span> pick: <span class="hljs-type">Path</span> => <span class="hljs-type">Rule</span>[<span class="hljs-type">I</span>, <span class="hljs-type">I</span>], coerce: <span class="hljs-type">Rule</span>[<span class="hljs-type">I</span>, <span class="hljs-type">J</span>]): <span class="hljs-type">Path</span> = <span class="hljs-type">Rule</span>[<span class="hljs-type">I</span>, <span class="hljs-type">O</span>]
</code></pre>
<ul>
<li><code>noneValues</code> is a List of all the values we should consider to be <code>None</code>. For Json that would be <code>JsNull</code>.</li>
<li><code>pick</code> is an extractor. It's going to extract a subtree.</li>
<li><code>coerce</code> is a type conversion <code>Rule</code></li>
<li><code>r</code> is a <code>Rule</code> to be applied to the data if they are found</li>
</ul>
<p>All you have to do is to use this method to implement a specialized version for your type.
For example it's defined this way for Json:</p>
<pre><code class="lang-scala"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">optionR</span></span>[<span class="hljs-type">J</span>, <span class="hljs-type">O</span>](r: => <span class="hljs-type">Rule</span>[<span class="hljs-type">J</span>, <span class="hljs-type">O</span>], noneValues: <span class="hljs-type">Rule</span>[<span class="hljs-type">JsValue</span>, <span class="hljs-type">JsValue</span>]*)(<span class="hljs-keyword">implicit</span> pick: <span class="hljs-type">Path</span> => <span class="hljs-type">Rule</span>[<span class="hljs-type">JsValue</span>, <span class="hljs-type">JsValue</span>], coerce: <span class="hljs-type">Rule</span>[<span class="hljs-type">JsValue</span>, <span class="hljs-type">J</span>]): <span class="hljs-type">Path</span> => <span class="hljs-type">Rule</span>[<span class="hljs-type">JsValue</span>, <span class="hljs-type">Option</span>[<span class="hljs-type">O</span>]]
= <span class="hljs-keyword">super</span>.opt[<span class="hljs-type">J</span>, <span class="hljs-type">O</span>](r, (jsNull.map(n => n: <span class="hljs-type">JsValue</span>) +: noneValues):_*)
</code></pre>
<p>Basically it's just the same, but we are now only supporting <code>JsValue</code>. We are also adding JsNull is the list of None-ish values.</p>
<p>Despite the type signature funkiness, this function is actually <strong>really</strong> simple to use:</p>
<pre><code class="lang-scala"><span class="hljs-keyword">val</span> maybeEmail: <span class="hljs-type">Rule</span>[<span class="hljs-type">JsValue</span>, <span class="hljs-type">Option</span>[<span class="hljs-type">String</span>]] = <span class="hljs-type">From</span>[<span class="hljs-type">JsValue</span>] { __ =>
<span class="hljs-keyword">import</span> jto.validation.playjson.<span class="hljs-type">Rules</span>._
(__ \ <span class="hljs-string">"email"</span>).read(optionR(email))
}
</code></pre>
<pre><code class="lang-scala">scala> maybeEmail.validate(<span class="hljs-type">Json</span>.obj(<span class="hljs-string">"email"</span> -> <span class="hljs-string">"foo@bar.com"</span>))
res1: jto.validation.<span class="hljs-type">VA</span>[<span class="hljs-type">Option</span>[<span class="hljs-type">String</span>]] = <span class="hljs-type">Valid</span>(<span class="hljs-type">Some</span>(foo<span class="hljs-meta">@bar</span>.com))
scala> maybeEmail.validate(<span class="hljs-type">Json</span>.obj(<span class="hljs-string">"email"</span> -> <span class="hljs-string">"baam!"</span>))
res2: jto.validation.<span class="hljs-type">VA</span>[<span class="hljs-type">Option</span>[<span class="hljs-type">String</span>]] = <span class="hljs-type">Invalid</span>(<span class="hljs-type">List</span>((/email,<span class="hljs-type">List</span>(<span class="hljs-type">ValidationError</span>(<span class="hljs-type">List</span>(error.email),<span class="hljs-type">WrappedArray</span>())))))
scala> maybeEmail.validate(<span class="hljs-type">Json</span>.obj(<span class="hljs-string">"email"</span> -> <span class="hljs-type">JsNull</span>))
res3: jto.validation.<span class="hljs-type">VA</span>[<span class="hljs-type">Option</span>[<span class="hljs-type">String</span>]] = <span class="hljs-type">Valid</span>(<span class="hljs-type">None</span>)
scala> maybeEmail.validate(<span class="hljs-type">Json</span>.obj())
res4: jto.validation.<span class="hljs-type">VA</span>[<span class="hljs-type">Option</span>[<span class="hljs-type">String</span>]] = <span class="hljs-type">Valid</span>(<span class="hljs-type">None</span>)
</code></pre>
<p>Alright, so now we can explicitly define rules for optional data.</p>
<p>But what if we write <code>(__ \ "age").read[Option[Int]]</code>? It does not compile!
We need to define an implicit rule for that:</p>
<pre><code class="lang-scala"><span class="hljs-keyword">implicit</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">option</span></span>[<span class="hljs-type">O</span>](p: <span class="hljs-type">Path</span>)(<span class="hljs-keyword">implicit</span> pick: <span class="hljs-type">Path</span> => <span class="hljs-type">Rule</span>[<span class="hljs-type">JsValue</span>, <span class="hljs-type">JsValue</span>], coerce: <span class="hljs-type">Rule</span>[<span class="hljs-type">JsValue</span>, <span class="hljs-type">O</span>]): <span class="hljs-type">Rule</span>[<span class="hljs-type">JsValue</span>, <span class="hljs-type">Option</span>[<span class="hljs-type">O</span>]] =
option(<span class="hljs-type">Rule</span>.zero[<span class="hljs-type">O</span>])(pick, coerce)(p)
</code></pre>
<pre><code class="lang-scala"><span class="hljs-keyword">val</span> maybeAge: <span class="hljs-type">Rule</span>[<span class="hljs-type">JsValue</span>, <span class="hljs-type">Option</span>[<span class="hljs-type">Int</span>]] = <span class="hljs-type">From</span>[<span class="hljs-type">JsValue</span>] { __ =>
<span class="hljs-keyword">import</span> jto.validation.playjson.<span class="hljs-type">Rules</span>._
(__ \ <span class="hljs-string">"age"</span>).read[<span class="hljs-type">Option</span>[<span class="hljs-type">Int</span>]]
}
</code></pre>
<h3 id="lazyness">Lazyness</h3>
<p>It's very important that every Rule is completely lazily evaluated . The reason for that is that you may be validating recursive types:</p>
<pre><code class="lang-scala">scala> <span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RecUser</span>(<span class="hljs-params">name: <span class="hljs-type">String</span>, friends: <span class="hljs-type">Seq</span>[<span class="hljs-type">RecUser</span>] = <span class="hljs-type">Nil</span></span>)</span>
defined <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RecUser</span></span>
scala> <span class="hljs-keyword">val</span> u = <span class="hljs-type">RecUser</span>(
| <span class="hljs-string">"bob"</span>,
| <span class="hljs-type">Seq</span>(<span class="hljs-type">RecUser</span>(<span class="hljs-string">"tom"</span>)))
u: <span class="hljs-type">RecUser</span> = <span class="hljs-type">RecUser</span>(bob,<span class="hljs-type">List</span>(<span class="hljs-type">RecUser</span>(tom,<span class="hljs-type">List</span>())))
scala> <span class="hljs-keyword">lazy</span> <span class="hljs-keyword">val</span> w: <span class="hljs-type">Rule</span>[<span class="hljs-type">JsValue</span>, <span class="hljs-type">RecUser</span>] = <span class="hljs-type">From</span>[<span class="hljs-type">JsValue</span>] { __ =>
| <span class="hljs-keyword">import</span> jto.validation.playjson.<span class="hljs-type">Rules</span>._
| ((__ \ <span class="hljs-string">"name"</span>).read[<span class="hljs-type">String</span>] ~
| (__ \ <span class="hljs-string">"friends"</span>).read(seqR(w)))(<span class="hljs-type">RecUser</span>.apply) <span class="hljs-comment">// !!! recursive rule definition</span>
| }
w: jto.validation.<span class="hljs-type">Rule</span>[play.api.libs.json.<span class="hljs-type">JsValue</span>,<span class="hljs-type">RecUser</span>] = <<span class="hljs-keyword">lazy</span>>
</code></pre>
<h2 id="writes">Writes</h2>
<p>Writes are implemented in a similar fashion, but a generally easier to implement. You start by defining a function for writing at a given path:</p>
<pre><code class="lang-scala">scala> {
| <span class="hljs-keyword">implicit</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">writeJson</span></span>[<span class="hljs-type">I</span>](path: <span class="hljs-type">Path</span>)(<span class="hljs-keyword">implicit</span> w: <span class="hljs-type">Write</span>[<span class="hljs-type">I</span>, <span class="hljs-type">JsValue</span>]): <span class="hljs-type">Write</span>[<span class="hljs-type">I</span>, <span class="hljs-type">JsObject</span>] = ???
| }
</code></pre>
<p>And you then define all the primitive writes:</p>
<pre><code class="lang-scala">scala> {
| <span class="hljs-keyword">implicit</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">anyval</span></span>[<span class="hljs-type">T</span> <: <span class="hljs-type">AnyVal</span>] = ???
| }
</code></pre>
<h3 id="monoid">Monoid</h3>
<p>In order to be able to use writes combinators, you also need to create an implementation of <code>Monoid</code> for your output type. For example, to create a complex write of <code>JsObject</code>, we had to implement a <code>Monoid[JsObject]</code>:</p>
<pre><code class="lang-scala">scala> {
| <span class="hljs-keyword">import</span> cats.<span class="hljs-type">Monoid</span>
| <span class="hljs-keyword">implicit</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">jsonMonoid</span> </span>= <span class="hljs-keyword">new</span> <span class="hljs-type">Monoid</span>[<span class="hljs-type">JsObject</span>] {
| <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">combine</span></span>(a1: <span class="hljs-type">JsObject</span>, a2: <span class="hljs-type">JsObject</span>) = a1 deepMerge a2
| <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">empty</span> </span>= <span class="hljs-type">Json</span>.obj()
| }
| }
</code></pre>
<p>from there you're able to create complex writes like:</p>
<pre><code class="lang-scala"><span class="hljs-keyword">import</span> jto.validation._
<span class="hljs-keyword">import</span> play.api.libs.json._
<span class="hljs-keyword">import</span> scala.<span class="hljs-type">Function</span>.unlift
<span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>(<span class="hljs-params">
name: <span class="hljs-type">String</span>,
age: <span class="hljs-type">Int</span>,
email: <span class="hljs-type">Option</span>[<span class="hljs-type">String</span>],
isAlive: <span class="hljs-type">Boolean</span></span>)</span>
<span class="hljs-keyword">val</span> userWrite = <span class="hljs-type">To</span>[<span class="hljs-type">JsObject</span>] { __ =>
<span class="hljs-keyword">import</span> jto.validation.playjson.<span class="hljs-type">Writes</span>._
((__ \ <span class="hljs-string">"name"</span>).write[<span class="hljs-type">String</span>] ~
(__ \ <span class="hljs-string">"age"</span>).write[<span class="hljs-type">Int</span>] ~
(__ \ <span class="hljs-string">"email"</span>).write[<span class="hljs-type">Option</span>[<span class="hljs-type">String</span>]] ~
(__ \ <span class="hljs-string">"isAlive"</span>).write[<span class="hljs-type">Boolean</span>])(unlift(<span class="hljs-type">User</span>.unapply))
}
</code></pre>
<h2 id="testing">Testing</h2>
<p>We highly recommend you to test your rules as much as possible. There're a few tricky cases you need to handle properly. You should port the tests in <code>RulesSpec.scala</code> and use them on your rules.</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="ScalaJsValidation.html" class="navigation navigation-prev " aria-label="Previous page: Exporting Validations to Javascript using Scala.js">
<i class="fa fa-angle-left"></i>
</a>
<a href="ScalaValidationCookbook.html" class="navigation navigation-next " aria-label="Next page: Cookbook">
<i class="fa fa-angle-right"></i>
</a>
</div>
<script>
var gitbook = gitbook || [];
gitbook.push(function() {
gitbook.page.hasChanged({"page":{"title":"Extensions: Supporting new types","level":"1.2.7","depth":2,"next":{"title":"Cookbook","level":"1.2.8","depth":2,"path":"ScalaValidationCookbook.md","ref":"ScalaValidationCookbook.md","articles":[]},"previous":{"title":"Exporting Validations to Javascript using Scala.js","level":"1.2.6","depth":2,"path":"ScalaJsValidation.md","ref":"ScalaJsValidation.md","articles":[]},"dir":"ltr"},"config":{"gitbook":"*","theme":"default","variables":{},"plugins":[],"pluginsConfig":{"highlight":{},"search":{},"lunr":{"maxIndexSize":1000000},"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}},"structure":{"langs":"LANGS.md","readme":"README.md","glossary":"GLOSSARY.md","summary":"SUMMARY.md"},"pdf":{"pageNumbers":true,"fontSize":12,"fontFamily":"Arial","paperSize":"a4","chapterMark":"pagebreak","pageBreaksBefore":"/","margin":{"right":62,"left":62,"top":56,"bottom":56}},"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"}},"file":{"path":"ScalaValidationExtensions.md","mtime":"2016-06-24T15:39:52.000Z","type":"markdown"},"gitbook":{"version":"3.0.2","time":"2016-06-24T15:40:18.647Z"},"basePath":".","book":{"language":""}});
});
</script>
</div>
<script src="gitbook/gitbook.js"></script>
<script src="gitbook/theme.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/buttons.js"></script>
</body>
</html>