Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot generate auto encoder for Microsoft.FSharp.Core.Unit. Please pass an extra encoder

I have created a helper function for returning Thoth.Json style json from my Giraffe project that takes a Result<'a,'b> and returns JSON.

let json result next (ctx: HttpContext) =
     match result with
            | Ok result ->
                    (setHttpHeader "Content-Type" "application/json" >=>
                        setBodyFromString (Encode.Auto.toString (0, result))) next ctx
            | Error e -> ...

This works fine until I return Ok (), which compiles and should be perfectly valid.

However, Thoth.Json is not so fond of it:

Cannot generate auto encoder for Microsoft.FSharp.Core.Unit. Please pass an extra encoder.

How can I either check if result is a unit or make the auto encoder handle unit ?

like image 964
severin Avatar asked Nov 18 '25 10:11

severin


1 Answers

I had the same problem today, solved it by creating custom Encoder<'T> and Decoder<T>. Funnily, this was not necessary a month ago and I would have sworn I did not update anything.

This is how the encoder looks like, you can use any JSON as return value.

open Thoth.Json.Net

module UnitEncoder =

    let encoder = fun _ -> JsonValue.Parse("null")

    let decoder = fun _ _ -> Ok ()

You can define the serializer like this

let extraCoders =
    Extra.empty
    |> Extra.withDecimal
    |> Extra.withCustom UnitEncoder.encoder UnitEncoder.decoder


let serializer = Thoth.Json.Giraffe.ThothSerializer(extra = extraCoders)

and register it as a service as usual

services.AddSingleton<Giraffe.Serialization.Json.IJsonSerializer>(CN.ReportingServices.API.Serialization.serializer) |> ignore
like image 165
Karel Stastny Avatar answered Nov 20 '25 12:11

Karel Stastny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!