optionalFieldOrNullWithOmittedDefault

This commit is contained in:
Tom Sydney Kerckhove 2021-11-14 13:12:07 +01:00
parent 3af2f4b216
commit 9cb3e6995c
3 changed files with 54 additions and 1 deletions

View File

@ -9,7 +9,6 @@ module Autodocodec.Aeson.Decode where
import Autodocodec.Class
import Autodocodec.Codec
import Autodocodec.DerivingVia
import Control.Applicative
import Control.Monad
import Data.Aeson as JSON
import Data.Aeson.Types as JSON

View File

@ -270,3 +270,23 @@ optionalFieldWithOmittedDefault' ::
output ->
ObjectCodec output output
optionalFieldWithOmittedDefault' key defaultValue = optionalFieldWithOmittedDefaultWith' key codec defaultValue
optionalFieldOrNullWithOmittedDefault ::
(Eq output, HasCodec output) =>
-- | Key
Text ->
-- | Default value
output ->
-- | Documentation
Text ->
ObjectCodec output output
optionalFieldOrNullWithOmittedDefault key defaultValue doc = optionalFieldOrNullWithOmittedDefaultWith key codec defaultValue doc
optionalFieldOrNullWithOmittedDefault' ::
(Eq output, HasCodec output) =>
-- | Key
Text ->
-- | Default value
output ->
ObjectCodec output output
optionalFieldOrNullWithOmittedDefault' key defaultValue = optionalFieldOrNullWithOmittedDefaultWith' key codec defaultValue

View File

@ -569,6 +569,40 @@ optionalFieldWithOmittedDefaultWith' ::
ObjectCodec output output
optionalFieldWithOmittedDefaultWith' key c defaultValue = OptionalKeyWithOmittedDefaultCodec key c defaultValue Nothing
optionalFieldOrNullWithOmittedDefaultWith ::
Eq output =>
-- | Key
Text ->
-- | Codec for the value
JSONCodec output ->
-- | Default value
output ->
-- | Documentation
Text ->
ObjectCodec output output
optionalFieldOrNullWithOmittedDefaultWith key c defaultValue doc = dimapCodec f g $ optionalFieldWithOmittedDefaultWith key (maybeCodec c) (Just defaultValue) doc
where
f = \case
Just v -> v
Nothing -> defaultValue
g v = if v == defaultValue then Nothing else Just v
optionalFieldOrNullWithOmittedDefaultWith' ::
Eq output =>
-- | Key
Text ->
-- | Codec for the value
JSONCodec output ->
-- | Default value
output ->
ObjectCodec output output
optionalFieldOrNullWithOmittedDefaultWith' key c defaultValue = dimapCodec f g $ optionalFieldWithOmittedDefaultWith' key (maybeCodec c) (Just defaultValue)
where
f = \case
Just v -> v
Nothing -> defaultValue
g v = if v == defaultValue then Nothing else Just v
-- | An optional, or null, field
--
-- During decoding, the field may be in the object. 'Nothing' will be parsed if it is not.