alloy.Discriminated.scala Maven / Gradle / Ivy
package alloy
import smithy4s.Hints
import smithy4s.Newtype
import smithy4s.Schema
import smithy4s.ShapeId
import smithy4s.schema.Schema.bijection
import smithy4s.schema.Schema.recursive
import smithy4s.schema.Schema.string
/** Discriminated unions contain the information about which
* branch of a union is encoded inside of the object itself.
* The following union:
* structure One {
* a: Int
* }
* structure Two {
* b: String
* }
* union Test {
* one: One
* two: Two
* }
* would normally be encoded in JSON as:
* { "one": { "a": 123 } }
* when annotated with `{@literal @}discriminated("type")`, it will
* instead be encoded as:
* { "a": 123, "type": "one" }
* This is more efficient than using an untagged encoding,
* but less efficient than using the default tagged union
* encoding. Therefore, it should only be used when necessary.
* Tagged union encodings should be used wherever possible.
*/
object Discriminated extends Newtype[String] {
val id: ShapeId = ShapeId("alloy", "discriminated")
val hints: Hints = Hints(
smithy.api.Documentation("Discriminated unions contain the information about which\nbranch of a union is encoded inside of the object itself.\nThe following union:\nstructure One {\n a: Int\n}\nstructure Two {\n b: String\n}\nunion Test {\n one: One\n two: Two \n}\nwould normally be encoded in JSON as:\n{ \"one\": { \"a\": 123 } }\nwhen annotated with `@discriminated(\"type\")`, it will\ninstead be encoded as:\n{ \"a\": 123, \"type\": \"one\" }\nThis is more efficient than using an untagged encoding,\nbut less efficient than using the default tagged union\nencoding. Therefore, it should only be used when necessary.\nTagged union encodings should be used wherever possible."),
smithy.api.Trait(selector = Some("union :not([trait|alloy#untagged])"), structurallyExclusive = None, conflicts = None, breakingChanges = None),
).lazily
val underlyingSchema: Schema[String] = string.withId(id).addHints(hints)
implicit val schema: Schema[Discriminated] = recursive(bijection(underlyingSchema, asBijection))
}