Skip to content

Commit

Permalink
UnionConverter: Accept custom discriminator without catchAllCase (#51)
Browse files Browse the repository at this point in the history
  • Loading branch information
bartelink committed May 25, 2020
1 parent d01be6c commit 32fefb1
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ The `Unreleased` section name is replaced by the expected version of next releas
### Removed
### Fixed

- `UnionConverter`: Support overriding discriminator without needing to nominate a `catchAllCase` [#51](https://github.com/jet/FsCodec/pull/51)

<a name="2.1.0"></a>
## [2.1.0] - 2020-05-10

Expand Down
5 changes: 3 additions & 2 deletions src/FsCodec.NewtonsoftJson/UnionConverter.fs
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,9 @@ module private Union =
type UnionConverter private (discriminator : string, ?catchAllCase) =
inherit JsonConverter()

new() = UnionConverter("case")
new(discriminator: string, catchAllCase: string) = UnionConverter(discriminator, ?catchAllCase = match catchAllCase with null -> None | x -> Some x)
new() = UnionConverter("case", ?catchAllCase=None)
new(discriminator: string) = UnionConverter(discriminator, ?catchAllCase=None)
new(discriminator: string, catchAllCase: string) = UnionConverter(discriminator, ?catchAllCase=match catchAllCase with null -> None | x -> Some x)

override __.CanConvert (t : Type) = Union.isUnion t

Expand Down
20 changes: 20 additions & 0 deletions tests/FsCodec.NewtonsoftJson.Tests/UnionConverterTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,26 @@ let ``Implementation ensures no internal errors escape (which would render a Web
test <@ (CaseD "hi") = d @>
test <@ false = gotError @>

module CustomDiscriminator =

[<JsonConverter(typeof<UnionConverter>, "esac")>]
type DuWithCustomDiscriminator =
| Known
| Catchall

[<Fact>]
let ``UnionConverter handles custom discriminator`` () =
let json = """{"esac":"Known"}"""
test <@ DuWithCustomDiscriminator.Known = JsonConvert.DeserializeObject<_> json @>

[<Fact>]
let ``UnionConverter can complain about missing case with custom discriminator without catchall`` () =
let aJson = """{"esac":"CaseUnknown"}"""
let act () = JsonConvert.DeserializeObject<DuWithCustomDiscriminator>(aJson, settings)

fun (e : System.InvalidOperationException) -> <@ -1 <> e.Message.IndexOf "No case defined for 'CaseUnknown', and no catchAllCase nominated" @>
|> raisesWith <@ act() @>

module ``Unmatched case handling`` =

[<Fact>]
Expand Down

0 comments on commit 32fefb1

Please sign in to comment.