njlr / thoth-json-codec

Codec support for Thoth.Json
MIT License
7 stars 1 forks source link

skippable optional helper #7

Open joprice opened 3 months ago

joprice commented 3 months ago

It would be convenient to have a helper that allows avoiding writing nulls into the output, as it can save large amounts of storage and data transfer. Also, some pre-existing data formats don't include the null fields, so it can be necessary to distinguish them. This approach seems to work but curious about your thoughts:

module Codec =
    let fieldOpt
      (fieldName: string)
      (picker: 'u -> 't option)
      (fieldCodec: Codec<'t>)
      : ObjectCodecFieldSet<'t option, 'u>
      =
      {
        Values =
          fun i ->
            match i with
            | Some value -> [ fieldName, fieldCodec.Encoder value ]
            | None -> []
        Decoder = Decode.optional fieldName fieldCodec.Decoder
        Picker = picker
      }