refactor out an orNull helper

This commit is contained in:
Tom Sydney Kerckhove 2021-10-30 20:28:06 +02:00
parent 6f0851ad12
commit d7254410d2
2 changed files with 10 additions and 15 deletions

View File

@ -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

View File

@ -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