forked from endpoints4s/endpoints4s
/
JsonSchemas.scala
328 lines (289 loc) · 10 KB
/
JsonSchemas.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
package endpoints.playjson
import endpoints.{PartialInvariantFunctor, Tupler, Validated, algebra}
import play.api.libs.functional.syntax._
import play.api.libs.json._
import scala.collection.compat._
/**
* An interpreter for [[endpoints.algebra.JsonSchemas]] that produces Play JSON `play.api.libs.json.Reads`
* and `play.api.libs.json.Writes`.
*/
trait JsonSchemas extends algebra.JsonSchemas with TuplesSchemas {
trait JsonSchema[A] {
def reads: Reads[A]
def writes: Writes[A]
}
object JsonSchema {
def apply[A](_reads: Reads[A], _writes: Writes[A]): JsonSchema[A] =
new JsonSchema[A] {
def reads: Reads[A] = _reads
def writes: Writes[A] = _writes
}
implicit def toPlayJsonFormat[A](
implicit jsonSchema: JsonSchema[A]
): Format[A] =
Format(jsonSchema.reads, jsonSchema.writes)
}
implicit def jsonSchemaPartialInvFunctor
: PartialInvariantFunctor[JsonSchema] =
new PartialInvariantFunctor[JsonSchema] {
def xmapPartial[A, B](
fa: JsonSchema[A],
f: A => Validated[B],
g: B => A
): JsonSchema[B] =
JsonSchema(
fa.reads.flatMap(a =>
f(a).fold(
Reads.pure(_),
errors => Reads.failed(errors.mkString(". "))
)
),
fa.writes.contramap(g)
)
override def xmap[A, B](
fa: JsonSchema[A],
f: A => B,
g: B => A
): JsonSchema[B] =
JsonSchema(fa.reads.map(f), fa.writes.contramap(g))
}
trait Record[A] extends JsonSchema[A] {
override def writes: OWrites[A]
}
object Record {
def apply[A](_reads: Reads[A], _writes: OWrites[A]): Record[A] =
new Record[A] {
def reads: Reads[A] = _reads
def writes: OWrites[A] = _writes
}
implicit def toPlayJsonOFormat[A](implicit record: Record[A]): OFormat[A] =
OFormat(record.reads, record.writes)
}
implicit def recordPartialInvFunctor: PartialInvariantFunctor[Record] =
new PartialInvariantFunctor[Record] {
def xmapPartial[A, B](
fa: Record[A],
f: A => Validated[B],
g: B => A
): Record[B] =
Record(
fa.reads.flatMap(a =>
f(a).fold(
Reads.pure(_),
errors => Reads.failed(errors.mkString(". "))
)
),
fa.writes.contramap(g)
)
override def xmap[A, B](fa: Record[A], f: A => B, g: B => A): Record[B] =
Record(fa.reads.map(f), fa.writes.contramap(g))
}
type Enum[A] = JsonSchema[A]
def enumeration[A](values: Seq[A])(jsonSchema: JsonSchema[A]): Enum[A] = {
JsonSchema(
jsonSchema.reads.flatMap { a =>
if (values.contains(a)) {
Reads.pure(a)
} else {
Reads.failed(
s"Invalid value: ${Json.stringify(jsonSchema.writes.writes(a))} ; valid values are: ${values
.map(a => Json.stringify(jsonSchema.writes.writes(a)))
.mkString(", ")}"
)
}
},
jsonSchema.writes
)
}
def namedRecord[A](schema: Record[A], name: String): Record[A] = schema
def namedTagged[A](schema: Tagged[A], name: String): Tagged[A] = schema
def namedEnum[A](schema: Enum[A], name: String): Enum[A] = schema
private def lazySchema[A](
schema: => JsonSchema[A],
name: String
): JsonSchema[A] = {
// The schema won’t be evaluated until its `reads` or `writes` is effectively used
lazy val evaluatedSchema = schema
new JsonSchema[A] {
def reads: Reads[A] = Reads(js => evaluatedSchema.reads.reads(js))
def writes: Writes[A] = Writes(a => evaluatedSchema.writes.writes(a))
}
}
def lazyRecord[A](schema: => Record[A], name: String): JsonSchema[A] =
lazySchema(schema, name)
def lazyTagged[A](schema: => Tagged[A], name: String): JsonSchema[A] =
lazySchema(schema, name)
def emptyRecord: Record[Unit] =
Record(
new Reads[Unit] {
def reads(json: JsValue): JsResult[Unit] = json match {
case JsObject(_) => JsSuccess(())
case _ => JsError(s"Invalid JSON object: $json")
}
},
new OWrites[Unit] {
def writes(o: Unit): JsObject = Json.obj()
}
)
def field[A](name: String, documentation: Option[String] = None)(
implicit tpe: JsonSchema[A]
): Record[A] =
Record(
(__ \ name).read(tpe.reads),
(__ \ name).write(tpe.writes)
)
def optField[A](name: String, documentation: Option[String] = None)(
implicit tpe: JsonSchema[A]
): Record[Option[A]] =
Record(
(__ \ name).readNullable(tpe.reads),
(__ \ name).writeNullable(tpe.writes)
)
def withExampleJsonSchema[A](
schema: JsonSchema[A],
example: A
): JsonSchema[A] = schema
def orFallbackToJsonSchema[A, B](
schemaA: JsonSchema[A],
schemaB: JsonSchema[B]
): JsonSchema[Either[A, B]] = {
val reads =
schemaA.reads
.map[Either[A, B]](Left(_))
.orElse(schemaB.reads.map[Either[A, B]](Right(_)))
.orElse(Reads(json => JsError(s"Invalid value: $json")))
val writes =
Writes[Either[A, B]] {
case Left(a) => schemaA.writes.writes(a)
case Right(b) => schemaB.writes.writes(b)
}
JsonSchema(reads, writes)
}
def stringJsonSchema(format: Option[String]): JsonSchema[String] =
JsonSchema(implicitly, implicitly)
implicit def intJsonSchema: JsonSchema[Int] =
JsonSchema(implicitly, implicitly)
implicit def longJsonSchema: JsonSchema[Long] =
JsonSchema(implicitly, implicitly)
implicit def bigdecimalJsonSchema: JsonSchema[BigDecimal] =
JsonSchema(implicitly, implicitly)
implicit def floatJsonSchema: JsonSchema[Float] =
JsonSchema(implicitly, implicitly)
implicit def doubleJsonSchema: JsonSchema[Double] =
JsonSchema(implicitly, implicitly)
implicit def booleanJsonSchema: JsonSchema[Boolean] =
JsonSchema(implicitly, implicitly)
implicit def byteJsonSchema: JsonSchema[Byte] =
JsonSchema(implicitly, implicitly)
implicit def arrayJsonSchema[C[X] <: Seq[X], A](
implicit jsonSchema: JsonSchema[A],
factory: Factory[A, C[A]]
): JsonSchema[C[A]] =
JsonSchema[C[A]](
Reads.traversableReads(factory, jsonSchema.reads),
Writes.iterableWrites2[A, C[A]](implicitly, jsonSchema.writes)
)
implicit def mapJsonSchema[A](
implicit jsonSchema: JsonSchema[A]
): JsonSchema[Map[String, A]] =
JsonSchema(
Reads.mapReads(jsonSchema.reads),
Writes.genericMapWrites(jsonSchema.writes)
)
def zipRecords[A, B](recordA: Record[A], recordB: Record[B])(
implicit t: Tupler[A, B]
): Record[t.Out] = {
val reads = (recordA.reads and recordB.reads).tupled.map {
case (a, b) => t(a, b)
}
val writes = new OWrites[t.Out] {
override def writes(o: t.Out): JsObject = t.unapply(o) match {
case (a, b) =>
recordA.writes.writes(a) deepMerge recordB.writes.writes(b)
}
}
Record(reads, writes)
}
trait Tagged[A] extends Record[A] {
def discriminator: String = defaultDiscriminatorName
def tagAndJson(a: A): (String, JsObject)
def findReads(tagName: String): Option[Reads[A]]
final def reads: Reads[A] = {
case jsObject @ JsObject(kvs) =>
kvs.get(discriminator) match {
case Some(JsString(tag)) =>
findReads(tag) match {
case Some(reads) => reads.reads(jsObject)
case None => JsError(s"no Reads for tag '$tag': $jsObject")
}
case _ =>
JsError(
s"expected discriminator field '$discriminator', but not found in: $jsObject"
)
}
case json =>
JsError(s"expected JSON object for tagged type, but found: $json")
}
final def writes: OWrites[A] = new OWrites[A] {
override def writes(a: A): JsObject = {
val (tag, json) = tagAndJson(a)
json + (discriminator -> JsString(tag))
}
}
}
implicit def taggedPartialInvFunctor: PartialInvariantFunctor[Tagged] =
new PartialInvariantFunctor[Tagged] {
def xmapPartial[A, B](
fa: Tagged[A],
f: A => Validated[B],
g: B => A
): Tagged[B] =
new Tagged[B] {
def tagAndJson(b: B): (String, JsObject) = fa.tagAndJson(g(b))
def findReads(tag: String): Option[Reads[B]] =
fa.findReads(tag)
.map(
_.flatMap(a =>
f(a).fold(
Reads.pure(_),
errors => Reads.failed(errors.mkString(". "))
)
)
)
}
override def xmap[A, B](fa: Tagged[A], f: A => B, g: B => A): Tagged[B] =
new Tagged[B] {
def tagAndJson(b: B): (String, JsObject) = fa.tagAndJson(g(b))
def findReads(tag: String): Option[Reads[B]] =
fa.findReads(tag).map(_.map(f))
}
}
def taggedRecord[A](recordA: Record[A], tag: String): Tagged[A] =
new Tagged[A] {
def tagAndJson(a: A): (String, JsObject) = (tag, recordA.writes.writes(a))
def findReads(tagName: String): Option[Reads[A]] =
if (tag == tagName) Some(recordA.reads) else None
}
def withDiscriminatorTagged[A](
tagged: Tagged[A],
discriminatorName: String
): Tagged[A] =
new Tagged[A] {
override def discriminator: String = discriminatorName
def tagAndJson(a: A): (String, JsObject) = tagged.tagAndJson(a)
def findReads(tagName: String): Option[Reads[A]] =
tagged.findReads(tagName)
}
def choiceTagged[A, B](
taggedA: Tagged[A],
taggedB: Tagged[B]
): Tagged[Either[A, B]] = new Tagged[Either[A, B]] {
def tagAndJson(aOrB: Either[A, B]): (String, JsObject) = aOrB match {
case Left(a) => taggedA.tagAndJson(a)
case Right(b) => taggedB.tagAndJson(b)
}
def findReads(tagName: String): Option[Reads[Either[A, B]]] =
taggedA.findReads(tagName).map(_.map[Either[A, B]](Left(_))) orElse
taggedB.findReads(tagName).map(_.map[Either[A, B]](Right(_)))
}
}