Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions tests/ObjectCodec.fs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ type Large =
Baz : Guid
}

type Baz = { Baz : string option }

module Codec =

let fooBar : Codec<FooBar> =
Expand Down Expand Up @@ -73,6 +75,13 @@ module Codec =
}
}

let baz : Codec<Baz> =
objectCodec {
let! baz = Codec.optional "baz" (fun x -> x.Baz) Codec.string

return { Baz = baz }
}

let tests =
testList
"ObjectCodec"
Expand Down Expand Up @@ -118,4 +127,19 @@ let tests =

Expect.equal actual expected "The decoded value must match the original"
}

test "objectCodec optional field works" {
let withValue = { Baz = Some "abc" }

let withoutValue = { Baz = None }

let actualWithValue =
roundTrip Codec.baz withValue

let actualWithoutValue =
roundTrip Codec.baz withoutValue

Expect.equal actualWithValue withValue "The decoded Some value must match the original"
Expect.equal actualWithoutValue withoutValue "The decoded None value must match the original"
}
]
14 changes: 14 additions & 0 deletions thoth-json-codec/Object.fs
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,17 @@ module ObjectCodecComputationExpression =
Decoder = Decode.field fieldName fieldCodec.Decoder
Picker = picker
}

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