The JSON schema of A, derived from the type itself so that it cannot drift from it.
case class Invoice(vendor: String, amount: Double, lines: List[String], note: Option[String]) derives SchemaOf
SchemaOf[Invoice].toJsonSchema() // the schema `completeStructured` sends
The schema describes what uPickle's derived ReadWriter reads and writes (field names, Option as the value or null, an enum as its case name, a BigDecimal as a string), so a reply that matches the schema reads back into A. The module's tests check that round trip for every supported shape.
Supported: String, Int, Long, Double, Float, Boolean, BigDecimal, BigInt; Option; List, Seq, Vector and Set of a supported type; case classes whose fields are supported; enums and sealed hierarchies of singletons (as a string with the case names, or a case's @upickle.implicits.key); and sum types, enums and sealed traits whose cases have fields (as a JSON Schema anyOf of one object per case, each with the discriminator uPickle writes: "$type", or the trait's @upickle.implicits.key, holding the case's tag); and named tuples, (city: String, days: Int), as an object with one property per element (see SchemaOf.namedTuple). Not supported, and refused at compile time with a message naming the type: Map (core's ObjectSchema has a fixed set of properties and cannot describe map values), recursive types (they need a JSON Schema $ref), a sealed hierarchy nested in another or with a generic case, and Option directly inside Option and tuples without names (uPickle writes both as JSON arrays). Other types need a given SchemaOf of their own: see SchemaOf.string and SchemaOf.stringEnum. A hand-written given is used as it is, so it can also describe a type the derivation would refuse.
A recursion that runs through hand-written givens which themselves call SchemaOf.derived (for mutually recursive P and Q, given SchemaOf[P] = SchemaOf.derived[P] and given SchemaOf[Q] = SchemaOf.derived[Q]) cannot be seen at compile time, because the check does not look inside a hand-written given. Building that schema (schema, definition, toJsonSchema) throws an IllegalStateException naming the recursive type instead, on first use; it never hangs.
A generic case class may be nested in itself at most 16 deep: W[W[...[Int]]] with 16 Ws is described, with 17 it is taken for a recursion. Spelled out in a field's type, the deeper nesting is refused at compile time; reached through the generic derives SchemaOf instance (SchemaOf[W[...[Int]]]) it is refused when the schema is built, with the same IllegalStateException.
A sum type with fields is core's AnyOfSchema: one alternative per case. A tool's arguments may hold one, but cannot be one, since a tool's arguments are a JSON object.
Type parameters
- A
-
the described type
Attributes
- Companion
- object
- Source
- SchemaOf.scala
- Graph
-
- Supertypes
