Add `src/Internal/Tools` folder
parent
6337c2cc03
commit
49f73bac4f
|
@ -0,0 +1,42 @@
|
|||
module Internal.Tools.DecodeExtra exposing (opField, opFieldWithDefault)
|
||||
|
||||
import Json.Decode as D
|
||||
|
||||
|
||||
{-| Add an optional field decoder. If the field exists, the decoder will fail
|
||||
if the field doesn't decode properly.
|
||||
|
||||
This decoder standard out from `D.maybe <| D.field fieldName decoder` because
|
||||
that will decode into a `Nothing` if the `decoder` fails. This function
|
||||
will only decode into a `Nothing` if the field doesn't exist, and will fail if
|
||||
`decoder` fails.
|
||||
|
||||
The function also returns Nothing if the field exists but it is null.
|
||||
|
||||
-}
|
||||
opField : String -> D.Decoder a -> D.Decoder (Maybe a)
|
||||
opField fieldName decoder =
|
||||
D.value
|
||||
|> D.field fieldName
|
||||
|> D.maybe
|
||||
|> D.andThen
|
||||
(\v ->
|
||||
case v of
|
||||
Just _ ->
|
||||
D.oneOf
|
||||
[ D.null Nothing
|
||||
, D.map Just decoder
|
||||
]
|
||||
|> D.field fieldName
|
||||
|
||||
Nothing ->
|
||||
D.succeed Nothing
|
||||
)
|
||||
|
||||
|
||||
{-| Add an optional field decoder. If the field is not given, the decoder will
|
||||
return a default value.
|
||||
-}
|
||||
opFieldWithDefault : String -> a -> D.Decoder a -> D.Decoder a
|
||||
opFieldWithDefault fieldName default decoder =
|
||||
opField fieldName decoder |> D.map (Maybe.withDefault default)
|
|
@ -0,0 +1,19 @@
|
|||
module Internal.Tools.EncodeExtra exposing (..)
|
||||
|
||||
import Json.Encode as E
|
||||
|
||||
|
||||
{-| Create a body object based on optionally provided values.
|
||||
-}
|
||||
maybeObject : List ( String, Maybe E.Value ) -> E.Value
|
||||
maybeObject =
|
||||
List.filterMap
|
||||
(\( name, value ) ->
|
||||
case value of
|
||||
Just v ->
|
||||
Just ( name, v )
|
||||
|
||||
_ ->
|
||||
Nothing
|
||||
)
|
||||
>> E.object
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,23 @@
|
|||
module Internal.Tools.Timestamp exposing (Timestamp, encodeTimestamp, timestampDecoder)
|
||||
|
||||
import Json.Decode as D
|
||||
import Json.Encode as E
|
||||
import Time
|
||||
|
||||
|
||||
type alias Timestamp =
|
||||
Time.Posix
|
||||
|
||||
|
||||
{-| Encode a timestamp
|
||||
-}
|
||||
encodeTimestamp : Timestamp -> E.Value
|
||||
encodeTimestamp =
|
||||
Time.posixToMillis >> E.int
|
||||
|
||||
|
||||
{-| Decode a timestmap
|
||||
-}
|
||||
timestampDecoder : D.Decoder Timestamp
|
||||
timestampDecoder =
|
||||
D.map Time.millisToPosix D.int
|
Loading…
Reference in New Issue