From 8d98ab2535cc2b6c837e1e2e7087941ca3763423 Mon Sep 17 00:00:00 2001 From: njlr Date: Sat, 6 Jun 2026 13:00:03 +0100 Subject: [PATCH 1/2] Adds Codec.optional --- tests/ObjectCodec.fs | 25 +++++++++++++++++++++++++ thoth-json-codec/Object.fs | 14 ++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/tests/ObjectCodec.fs b/tests/ObjectCodec.fs index a42d9c9..d018228 100644 --- a/tests/ObjectCodec.fs +++ b/tests/ObjectCodec.fs @@ -8,6 +8,7 @@ open Fable.Mocha open Expecto #endif +open Thoth.Json.Core open Thoth.Json.Codec open Thoth.Json.Codec.Tests @@ -31,6 +32,8 @@ type Large = Baz : Guid } +type Baz = { Baz : string option } + module Codec = let fooBar : Codec = @@ -73,6 +76,13 @@ module Codec = } } + let baz : Codec = + objectCodec { + let! baz = Codec.optional "baz" (fun x -> x.Baz) Codec.string + + return { Baz = baz } + } + let tests = testList "ObjectCodec" @@ -118,4 +128,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" + } ] diff --git a/thoth-json-codec/Object.fs b/thoth-json-codec/Object.fs index 853fee4..a9f2095 100644 --- a/thoth-json-codec/Object.fs +++ b/thoth-json-codec/Object.fs @@ -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 + } From 21e566d9b2bb1c79aad132e374b30194d86ef00c Mon Sep 17 00:00:00 2001 From: njlr Date: Sat, 6 Jun 2026 13:03:41 +0100 Subject: [PATCH 2/2] Unused import --- tests/ObjectCodec.fs | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/ObjectCodec.fs b/tests/ObjectCodec.fs index d018228..fdb1eb1 100644 --- a/tests/ObjectCodec.fs +++ b/tests/ObjectCodec.fs @@ -8,7 +8,6 @@ open Fable.Mocha open Expecto #endif -open Thoth.Json.Core open Thoth.Json.Codec open Thoth.Json.Codec.Tests