From 055624ebd638c4a557814d289fa1a738d42d0c7c Mon Sep 17 00:00:00 2001 From: webwarrior Date: Wed, 14 Feb 2024 13:00:52 +0100 Subject: [PATCH] Core: add json converters for F# types Implement JSON converters for F# Discriminated Union types because System.Text.Json can't serialize them out of the box. Without converters, got the following error: ``` System.NotSupportedException : F# discriminated union serialization is not supported. Consider authoring a custom converter for the type. The unsupported member type is located on type 'FsharpExchangeDotNetStandard.Currency'. Path: $.Market.BuyCurrency. ``` --- src/FX.Core/RedisStorageLayer.fs | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/src/FX.Core/RedisStorageLayer.fs b/src/FX.Core/RedisStorageLayer.fs index 00e03de..07a9070 100644 --- a/src/FX.Core/RedisStorageLayer.fs +++ b/src/FX.Core/RedisStorageLayer.fs @@ -6,11 +6,40 @@ open System open FsharpExchangeDotNetStandard open System.Text.Json +open System.Text.Json.Serialization open StackExchange.Redis [] module Serialization = - let serializationOptions = JsonSerializerOptions.Default + // TODO: use FSharp.SystemTextJson for Discriminated Union support, + // in that case custom type converters are no longer needed + type SideTypeConverter() = + inherit JsonConverter() + + override this.Read(reader, _typeToConvert, _options) = + reader.GetString() |> Side.Parse + + override this.Write(writer, value, _options ) = + writer.WriteStringValue(value.ToString()) + + type CurrencyTypeConverter() = + inherit JsonConverter() + + override this.Read(reader, _typeToConvert, _options) = + match reader.GetString() with + | "BTC" -> BTC + | "USD" -> USD + | unknownCurrency -> failwithf "Unknown currency: %s" unknownCurrency + + override this.Write(writer, value, _options ) = + writer.WriteStringValue(value.ToString()) + + let serializationOptions = + let options = JsonSerializerOptions() + options.Converters.Add(SideTypeConverter()) + options.Converters.Add(CurrencyTypeConverter()) + options + type OrderQuery = {