johnhungerford / generic-schema

2 stars 1 forks source link

Schema utilities #28

Closed johnhungerford closed 2 years ago

johnhungerford commented 2 years ago

The idea here is that a schema can provide a set of utilities for dealing with a given type, like auto-migration or serialization/deserialization.

case class SomeClass( int : Int, str : String, bool : Boolean )
case class NewClass( integer : Int, boolean : Boolean, string : String )

val schema = Default.withDsl { dsl =>
  import dsl.{*, given}

  Schema.derived[SomeClass]
}

val converter : SomeClass => NewClass = schema.withUtils( _.derivedConversion[ NewClass ] )

val someCase = SomeClass( 5, "hello", true )

val strValue= schema.withUtils { utils =>
  import utils.given // need selector implicits

  utils.retrieve( someCase )( "str" )
}

assert( strValue == "hello" )

val serializedValue = schema.withUtils { utils =>
  import utils.given // need serialization implicits

  utils.write[ String ]( someCase ) // only available if configured with a writer extension (e.g., upickle)
}

assert( serializedValue == """{"int":5,"str":"hello","bool":true}""" )
johnhungerford commented 2 years ago

closed with #89