From d7254410d2ce657ff47b9e4b29d6f35d1bc06ea2 Mon Sep 17 00:00:00 2001 From: Tom Sydney Kerckhove Date: Sat, 30 Oct 2021 20:28:06 +0200 Subject: [PATCH] refactor out an orNull helper --- autodocodec/src/Autodocodec/Class.hs | 20 ++++++-------------- autodocodec/src/Autodocodec/Codec.hs | 5 ++++- 2 files changed, 10 insertions(+), 15 deletions(-) diff --git a/autodocodec/src/Autodocodec/Class.hs b/autodocodec/src/Autodocodec/Class.hs index 52c427a..38e984c 100644 --- a/autodocodec/src/Autodocodec/Class.hs +++ b/autodocodec/src/Autodocodec/Class.hs @@ -194,18 +194,7 @@ optionalFieldOrNull :: -- | Documentation Text -> ObjectCodec (Maybe output) (Maybe output) -optionalFieldOrNull key doc = - dimapCodec f g $ OptionalKeyCodec key (maybeCodec codec) (Just doc) - where - f :: Maybe (Maybe output) -> Maybe output - f = \case - Nothing -> Nothing - Just Nothing -> Nothing - Just (Just a) -> Just a - g :: Maybe output -> Maybe (Maybe output) - g = \case - Nothing -> Nothing - Just a -> Just (Just a) +optionalFieldOrNull key doc = orNullHelper $ OptionalKeyCodec key (maybeCodec codec) (Just doc) -- | Like 'optionalFieldOrNull', but without documentation optionalFieldOrNull' :: @@ -214,8 +203,11 @@ optionalFieldOrNull' :: -- | Key Text -> ObjectCodec (Maybe output) (Maybe output) -optionalFieldOrNull' key = - dimapCodec f g $ OptionalKeyCodec key (maybeCodec codec) Nothing +optionalFieldOrNull' key = orNullHelper $ OptionalKeyCodec key (maybeCodec codec) Nothing + +-- Helper function for 'optionalFieldOrNull'. +orNullHelper :: ObjectCodec (Maybe (Maybe value)) (Maybe (Maybe value)) -> ObjectCodec (Maybe value) (Maybe value) +orNullHelper = dimapCodec f g where f :: Maybe (Maybe output) -> Maybe output f = \case diff --git a/autodocodec/src/Autodocodec/Codec.hs b/autodocodec/src/Autodocodec/Codec.hs index 32667da..c225041 100644 --- a/autodocodec/src/Autodocodec/Codec.hs +++ b/autodocodec/src/Autodocodec/Codec.hs @@ -320,7 +320,10 @@ eitherCodec :: ValueCodec (Either input1 input2) (Either output1 output2) eitherCodec = EitherCodec --- | Value or null. +-- | Also allow @null@ during decoding of a 'Maybe' value. +-- +-- During decoding, also accept a @null@ value as 'Nothing'. +-- During encoding, encode as usual. maybeCodec :: ValueCodec input output -> ValueCodec (Maybe input) (Maybe output) maybeCodec = dimapCodec f g . EitherCodec nullCodec where