/
JsPath.scala
544 lines (475 loc) · 19.6 KB
/
JsPath.scala
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
/*
* Copyright (C) 2009-2016 Lightbend Inc. <https://www.lightbend.com>
*/
package play.api.libs.json
import play.api.data.validation.ValidationError
sealed trait PathNode {
def apply(json: JsValue): List[JsValue]
def toJsonString: String
private[json] def splitChildren(json: JsValue): List[Either[(PathNode, JsValue), (PathNode, JsValue)]]
def set(json: JsValue, transform: JsValue => JsValue): JsValue
private[json] def toJsonField(value: JsValue): JsValue = value
}
case class RecursiveSearch(key: String) extends PathNode {
def apply(json: JsValue): List[JsValue] = json match {
case obj: JsObject => (json \\ key).toList
case arr: JsArray => (json \\ key).toList
case _ => Nil
}
override def toString = "//" + key
def toJsonString = "*" + key
/**
* First found, first set and never goes down after setting
*/
def set(json: JsValue, transform: JsValue => JsValue): JsValue = json match {
case obj: JsObject =>
var found = false
val o = JsObject(obj.fields.map {
case (k, v) =>
if (k == this.key) {
found = true
k -> transform(v)
} else k -> set(v, transform)
})
o
case _ => json
}
private[json] def splitChildren(json: JsValue) = json match {
case obj: JsObject => obj.fields.toList.map {
case (k, v) =>
if (k == this.key) Right(this -> v)
else Left(KeyPathNode(k) -> v)
}
case arr: JsArray =>
arr.value.toList.zipWithIndex.map { case (js, j) => Left(IdxPathNode(j) -> js) }
case _ => List()
}
}
case class KeyPathNode(key: String) extends PathNode {
def apply(json: JsValue): List[JsValue] = json match {
case obj: JsObject => List(json \ key).flatMap(_.toOption)
case _ => List()
}
override def toString = "/" + key
def toJsonString = "." + key
def set(json: JsValue, transform: JsValue => JsValue): JsValue = json match {
case obj: JsObject =>
var found = false
val o = JsObject(obj.fields.map {
case (k, v) =>
if (k == this.key) {
found = true
k -> transform(v)
} else k -> v
})
if (!found) o ++ Json.obj(this.key -> transform(Json.obj()))
else o
case _ => transform(json)
}
private[json] def splitChildren(json: JsValue) = json match {
case obj: JsObject => obj.fields.toList.map {
case (k, v) =>
if (k == this.key) Right(this -> v)
else Left(KeyPathNode(k) -> v)
}
case _ => List()
}
private[json] override def toJsonField(value: JsValue) = Json.obj(key -> value)
}
case class IdxPathNode(idx: Int) extends PathNode {
def apply(json: JsValue): List[JsValue] = json match {
case arr: JsArray => List(arr(idx)).flatMap(_.toOption)
case _ => List()
}
override def toString = "(%d)".format(idx)
def toJsonString = "[%d]".format(idx)
def set(json: JsValue, transform: JsValue => JsValue): JsValue = json match {
case arr: JsArray => JsArray(arr.value.zipWithIndex.map { case (js, j) => if (j == idx) transform(js) else js })
case _ => transform(json)
}
private[json] def splitChildren(json: JsValue) = json match {
case arr: JsArray => arr.value.toList.zipWithIndex.map {
case (js, j) =>
if (j == idx) Right(this -> js)
else Left(IdxPathNode(j) -> js)
}
case _ => List()
}
private[json] override def toJsonField(value: JsValue) = value
}
object JsPath extends JsPath(List.empty) {
// TODO implement it correctly (doesn't merge )
def createObj(pathValues: (JsPath, JsValue)*) = {
def buildSubPath(path: JsPath, value: JsValue) = {
def step(path: List[PathNode], value: JsValue): JsObject = {
path match {
case List() => value match {
case obj: JsObject => obj
case _ => throw new RuntimeException("when empty JsPath, expecting JsObject")
}
case List(p) => p match {
case KeyPathNode(key) => Json.obj(key -> value)
case _ => throw new RuntimeException("expected KeyPathNode")
}
case head :: tail => head match {
case KeyPathNode(key) => Json.obj(key -> step(tail, value))
case _ => throw new RuntimeException("expected KeyPathNode")
}
}
}
step(path.path, value)
}
pathValues.foldLeft(Json.obj()) { (obj, pv) =>
val (path, value) = (pv._1, pv._2)
val subobj = buildSubPath(path, value)
obj.deepMerge(subobj)
}
}
}
case class JsPath(path: List[PathNode] = List()) {
def \(child: String) = JsPath(path :+ KeyPathNode(child))
def \(child: Symbol) = JsPath(path :+ KeyPathNode(child.name))
def \\(child: String) = JsPath(path :+ RecursiveSearch(child))
def \\(child: Symbol) = JsPath(path :+ RecursiveSearch(child.name))
def apply(idx: Int): JsPath = JsPath(path :+ IdxPathNode(idx))
def \(idx: Int): JsPath = apply(idx)
def apply(json: JsValue): List[JsValue] = path.foldLeft(List(json))((s, p) => s.flatMap(p.apply))
def asSingleJsResult(json: JsValue): JsResult[JsValue] = this(json) match {
case Nil => JsError(Seq(this -> Seq(ValidationError("error.path.missing"))))
case List(js) => JsSuccess(js)
case _ :: _ => JsError(Seq(this -> Seq(ValidationError("error.path.result.multiple"))))
}
def asSingleJson(json: JsValue): JsLookupResult = this(json) match {
case Nil => JsUndefined("error.path.missing")
case List(js) => JsDefined(js)
case _ :: _ => JsUndefined("error.path.result.multiple")
}
def applyTillLast(json: JsValue): Either[JsError, JsResult[JsValue]] = {
def step(path: List[PathNode], json: JsValue): Either[JsError, JsResult[JsValue]] = path match {
case Nil => Left(JsError(Seq(this -> Seq(ValidationError("error.path.empty")))))
case List(node) => node(json) match {
case Nil => Right(JsError(Seq(this -> Seq(ValidationError("error.path.missing")))))
case List(js) => Right(JsSuccess(js))
case _ :: _ => Right(JsError(Seq(this -> Seq(ValidationError("error.path.result.multiple")))))
}
case head :: tail => head(json) match {
case Nil => Left(JsError(Seq(this -> Seq(ValidationError("error.path.missing")))))
case List(js) => step(tail, js)
case _ :: _ => Left(JsError(Seq(this -> Seq(ValidationError("error.path.result.multiple")))))
}
}
step(path, json)
}
override def toString = path.mkString
def toJsonString = path.foldLeft("obj")((acc, p) => acc + p.toJsonString)
def compose(other: JsPath) = JsPath(path ++ other.path)
def ++(other: JsPath) = this compose other
/**
* Simple Prune for simple path and only JsObject
*/
def prune(js: JsValue) = {
def stepNode(json: JsObject, node: PathNode): JsResult[JsObject] = {
node match {
case KeyPathNode(key) => JsSuccess(json - key)
case _ => JsError(JsPath(), ValidationError("error.expected.keypathnode"))
}
}
def filterPathNode(json: JsObject, node: PathNode, value: JsValue): JsResult[JsObject] = {
node match {
case KeyPathNode(key) => JsSuccess(JsObject(json.fields.filterNot(_._1 == key)) ++ Json.obj(key -> value))
case _ => JsError(JsPath(), ValidationError("error.expected.keypathnode"))
}
}
def step(json: JsObject, lpath: JsPath): JsResult[JsObject] = {
lpath.path match {
case Nil => JsSuccess(json)
case List(p) => stepNode(json, p).repath(lpath)
case head :: tail => head(json) match {
case Nil => JsError(lpath, ValidationError("error.path.missing"))
case List(js) =>
js match {
case o: JsObject =>
step(o, JsPath(tail)).repath(lpath).flatMap(value =>
filterPathNode(json, head, value)
)
case _ => JsError(lpath, ValidationError("error.expected.jsobject"))
}
case h :: t => JsError(lpath, ValidationError("error.path.result.multiple"))
}
}
}
js match {
case o: JsObject => step(o, this) match {
case s: JsSuccess[JsObject] => s.copy(path = this)
case e => e
}
case _ =>
JsError(this, ValidationError("error.expected.jsobject"))
}
}
/** Reads a T at JsPath */
def read[T](implicit r: Reads[T]): Reads[T] = Reads.at[T](this)(r)
/**
* Reads a Option[T] search optional or nullable field at JsPath (field not found or null is None
* and other cases are Error).
*
* It runs through JsValue following all JsPath nodes on JsValue except last node:
* - If one node in JsPath is not found before last node => returns JsError( "missing-path" )
* - If all nodes are found till last node, it runs through JsValue with last node =>
* - If last node is not found => returns None
* - If last node is found with value "null" => returns None
* - If last node is found => applies implicit Reads[T]
*/
def readNullable[T](implicit r: Reads[T]): Reads[Option[T]] = Reads.nullable[T](this)(r)
/**
* Reads a T at JsPath using the explicit Reads[T] passed by name which is useful in case of
* recursive case classes for ex.
*
* {{{
* case class User(id: Long, name: String, friend: User)
*
* implicit lazy val UserReads: Reads[User] = (
* (__ \ 'id).read[Long] and
* (__ \ 'name).read[String] and
* (__ \ 'friend).lazyRead(UserReads)
* )(User.apply _)
* }}}
*/
def lazyRead[T](r: => Reads[T]): Reads[T] = Reads(js => Reads.at[T](this)(r).reads(js))
/**
* Reads lazily a Option[T] search optional or nullable field at JsPath using the explicit Reads[T]
* passed by name which is useful in case of recursive case classes for ex.
*
* {{{
* case class User(id: Long, name: String, friend: Option[User])
*
* implicit lazy val UserReads: Reads[User] = (
* (__ \ 'id).read[Long] and
* (__ \ 'name).read[String] and
* (__ \ 'friend).lazyReadNullable(UserReads)
* )(User.apply _)
* }}}
*/
def lazyReadNullable[T](r: => Reads[T]): Reads[Option[T]] = Reads(js => Reads.nullable[T](this)(r).reads(js))
/** Pure Reads doesn't read anything but creates a JsObject based on JsPath with the given T value */
def read[T](t: T) = Reads.pure(t)
/** Writes a T at given JsPath */
def write[T](implicit w: Writes[T]): OWrites[T] = Writes.at[T](this)(w)
/**
* Writes a Option[T] at given JsPath
* If None => doesn't write the field (never writes null actually)
* else => writes the field using implicit Writes[T]
*/
def writeNullable[T](implicit w: Writes[T]): OWrites[Option[T]] = Writes.nullable[T](this)(w)
/**
* Writes a T at JsPath using the explicit Writes[T] passed by name which is useful in case of
* recursive case classes for ex
*
* {{{
* case class User(id: Long, name: String, friend: User)
*
* implicit lazy val UserReads: Reads[User] = (
* (__ \ 'id).write[Long] and
* (__ \ 'name).write[String] and
* (__ \ 'friend).lazyWrite(UserReads)
* )(User.apply _)
* }}}
*/
def lazyWrite[T](w: => Writes[T]): OWrites[T] = OWrites((t: T) => Writes.at[T](this)(w).writes(t))
/**
* Writes a Option[T] at JsPath using the explicit Writes[T] passed by name which is useful in case of
* recursive case classes for ex
*
* Please note that it's not writeOpt to be coherent with readNullable
*
* {{{
* case class User(id: Long, name: String, friend: Option[User])
*
* implicit lazy val UserReads: Reads[User] = (
* (__ \ 'id).write[Long] and
* (__ \ 'name).write[String] and
* (__ \ 'friend).lazyWriteNullable(UserReads)
* )(User.apply _)
* }}}
*/
def lazyWriteNullable[T](w: => Writes[T]): OWrites[Option[T]] = OWrites((t: Option[T]) => Writes.nullable[T](this)(w).writes(t))
/** Writes a pure value at given JsPath */
def write[T](t: T)(implicit w: Writes[T]): OWrites[JsValue] = Writes.pure(this, t)
/** Reads/Writes a T at JsPath using provided implicit Format[T] */
def format[T](implicit f: Format[T]): OFormat[T] = Format.at[T](this)(f)
/** Reads/Writes a T at JsPath using provided explicit Reads[T] and implicit Writes[T]*/
def format[T](r: Reads[T])(implicit w: Writes[T]): OFormat[T] = Format.at[T](this)(Format(r, w))
/** Reads/Writes a T at JsPath using provided explicit Writes[T] and implicit Reads[T]*/
def format[T](w: Writes[T])(implicit r: Reads[T]): OFormat[T] = Format.at[T](this)(Format(r, w))
/**
* Reads/Writes a T at JsPath using provided implicit Reads[T] and Writes[T]
*
* Please note we couldn't call it "format" to prevent conflicts
*/
def rw[T](implicit r: Reads[T], w: Writes[T]): OFormat[T] = Format.at[T](this)(Format(r, w))
/**
* Reads/Writes a Option[T] (optional or nullable field) at given JsPath
*
* @see JsPath.readNullable to see behavior in reads
* @see JsPath.writeNullable to see behavior in writes
*/
def formatNullable[T](implicit f: Format[T]): OFormat[Option[T]] = Format.nullable[T](this)(f)
/**
* Lazy Reads/Writes a T at given JsPath using implicit Format[T]
* (useful in case of recursive case classes).
*
* @see JsPath.lazyReadNullable to see behavior in reads
* @see JsPath.lazyWriteNullable to see behavior in writes
*/
def lazyFormat[T](f: => Format[T]): OFormat[T] = OFormat[T](lazyRead(f), lazyWrite(f))
/**
* Lazy Reads/Writes a Option[T] (optional or nullable field) at given JsPath using implicit Format[T]
* (useful in case of recursive case classes).
*
* @see JsPath.lazyReadNullable to see behavior in reads
* @see JsPath.lazyWriteNullable to see behavior in writes
*/
def lazyFormatNullable[T](f: => Format[T]): OFormat[Option[T]] = OFormat[Option[T]](lazyReadNullable(f), lazyWriteNullable(f))
/**
* Lazy Reads/Writes a T at given JsPath using explicit Reads[T] and Writes[T]
* (useful in case of recursive case classes).
*
* @see JsPath.lazyReadNullable to see behavior in reads
* @see JsPath.lazyWriteNullable to see behavior in writes
*/
def lazyFormat[T](r: => Reads[T], w: => Writes[T]): OFormat[T] = OFormat[T](lazyRead(r), lazyWrite(w))
/**
* Lazy Reads/Writes a Option[T] (optional or nullable field) at given JsPath using explicit Reads[T] and Writes[T]
* (useful in case of recursive case classes).
*
* @see JsPath.lazyReadNullable to see behavior in reads
* @see JsPath.lazyWriteNullable to see behavior in writes
*/
def lazyFormatNullable[T](r: => Reads[T], w: => Writes[T]): OFormat[Option[T]] = OFormat[Option[T]](lazyReadNullable(r), lazyWriteNullable(w))
private val self = this
object json {
/**
* (`__` \ 'key).json.pick[A <: JsValue] is a Reads[A] that:
* - picks the given value at the given JsPath (WITHOUT THE PATH) from the input JS
* - validates this element as an object of type A (inheriting JsValue)
* - returns a JsResult[A]
*
* Useful to pick a typed JsValue at a given JsPath
*
* Example :
* {{{
* val js = Json.obj("key1" -> "value1", "key2" -> 123)
* js.validate((__ \ 'key2).json.pick[JsNumber])
* => JsSuccess(JsNumber(123),/key2)
* }}}
*/
def pick[A <: JsValue](implicit r: Reads[A]): Reads[A] = Reads.jsPick(self)
/**
* (`__` \ 'key).json.pick is a Reads[JsValue] that:
* - picks the given value at the given JsPath (WITHOUT THE PATH) from the input JS
* - validates this element as an object of type JsValue
* - returns a JsResult[JsValue]
*
* Useful to pick a JsValue at a given JsPath
*
* Example :
* {{{
* val js = Json.obj("key1" -> "value1", "key2" -> "value2")
* js.validate((__ \ 'key2).json.pick)
* => JsSuccess("value2",/key2)
* }}}
*/
def pick: Reads[JsValue] = pick[JsValue]
/**
* (`__` \ 'key).json.pickBranch[A <: JsValue](readsOfA) is a Reads[JsObject] that:
* - copies the given branch (JsPath + relative JsValue) from the input JS at this given JsPath
* - validates this relative JsValue as an object of type A (inheriting JsValue) potentially modifying it
* - creates a JsObject from JsPath and validated JsValue
* - returns a JsResult[JsObject]
*
* Useful to create/validate an JsObject from a single JsPath (potentially modifying it)
*
* Example :
* {{{
* val js = Json.obj("key1" -> "value1", "key2" -> Json.obj( "key21" -> "value2") )
* js.validate( (__ \ 'key2).json.pickBranch[JsString]( (__ \ 'key21).json.pick[JsString].map( (js: JsString) => JsString(js.value ++ "3456") ) ) )
* => JsSuccess({"key2":"value23456"},/key2/key21)
* }}}
*/
def pickBranch[A <: JsValue](reads: Reads[A]): Reads[JsObject] = Reads.jsPickBranch[A](self)(reads)
/**
* (`__` \ 'key).json.pickBranch is a Reads[JsObject] that:
* - copies the given branch (JsPath + relative JsValue) from the input JS at this given JsPath
* - creates a JsObject from JsPath and JsValue
* - returns a JsResult[JsObject]
*
* Useful to create/validate an JsObject from a single JsPath (potentially modifying it)
*
* Example :
* {{{
* val js = Json.obj("key1" -> "value1", "key2" -> Json.obj( "key21" -> "value2") )
* js.validate( (__ \ 'key2).json.pickBranch )
* => JsSuccess({"key2":{"key21":"value2"}},/key2)
* }}}
*/
def pickBranch: Reads[JsObject] = Reads.jsPickBranch[JsValue](self)
/**
* (`__` \ 'key).put(fixedValue) is a Reads[JsObject] that:
* - creates a JsObject setting A (inheriting JsValue) at given JsPath
* - returns a JsResult[JsObject]
*
* This Reads doesn't care about the input JS and is mainly used to set a fixed at a given JsPath
* Please that A is passed by name allowing to use an expression reevaluated at each time.
*
* Example :
* {{{
* val js = Json.obj("key1" -> "value1", "key2" -> "value2")
* js.validate( (__ \ 'key3).json.put( { JsNumber((new java.util.Date).getTime()) } ) )
* => JsSuccess({"key3":1376419773171},)
* }}}
*/
def put(a: => JsValue): Reads[JsObject] = Reads.jsPut(self, a)
/**
* (`__` \ 'key).json.copyFrom(reads) is a Reads[JsObject] that:
* - copies a JsValue using passed Reads[A]
* - creates a new branch from JsPath and copies previous value into it
*
* Useful to copy a value from a Json branch into another branch
*
* Example :
* {{{
* val js = Json.obj("key1" -> "value1", "key2" -> "value2")
* js.validate( (__ \ 'key3).json.copyFrom((__ \ 'key2).json.pick))
* => JsSuccess({"key3":"value2"},/key2)
* }}}
*/
def copyFrom[A <: JsValue](reads: Reads[A]): Reads[JsObject] = Reads.jsCopyTo(self)(reads)
/**
* (`__` \ 'key).json.update(reads) is the most complex Reads[JsObject] but the most powerful:
* - copies the whole JsValue => A
* - applies the passed Reads[A] on JsValue => B
* - deep merges both JsValues (A ++ B) so B overwrites A identical branches
*
* Please note that if you have prune a branch in B, it is still in A so you'll see it in the result
*
* Example :
* {{{
* val js = Json.obj("key1" -> "value1", "key2" -> "value2")
* js.validate(__.json.update((__ \ 'key3).json.put(JsString("value3"))))
* => JsSuccess({"key1":"value1","key2":"value2","key3":"value3"},)
* }}}
*/
def update[A <: JsValue](reads: Reads[A]): Reads[JsObject] = Reads.jsUpdate(self)(reads)
/**
* (`__` \ 'key).json.prune is Reads[JsObject] that prunes the branch and returns remaining JsValue
*
* Example :
* {{{
* val js = Json.obj("key1" -> "value1", "key2" -> "value2")
* js.validate( (__ \ 'key2).json.prune )
* => JsSuccess({"key1":"value1"},/key2)
* }}}
*/
def prune: Reads[JsObject] = Reads.jsPrune(self)
}
}