edkelly303/elm-order-safe-json-object-decoders/1.0.0

NOTE: the latest version is 2.0.0

Json.Decode.Safe

constructor
-> validator
-> Decoder
{ recordType : constructor
, expectedFieldOrder : validator
, totalFieldCount : Zero
, gotFieldOrder : a -> Bool
}

Start constructing a record decoder.

You will need to supply a polymorphic record constructor function as both arguments to this function.

For example, if you want to decode a record like this:

type alias User =
    { firstName : String
    , lastName : String
    , pets : Int
    }

You will need to write a constructor function as follows:

userConstructor : a -> b -> c -> { firstName : a, lastName : b, pets : c }
userConstructor firstName lastName pets =
    { firstName = firstName
    , lastName = lastName
    , pets = pets
    }

Note: it is important that the type annotation does not constrain the types of the arguments passed into this constructor function. That is part of the secret of how this package works its magic!

Now, pass the polymorphic constructor function into record twice, like this:

import Json.Decode.Safe exposing (record, field)


userDecoder =
    record userConstructor userConstructor
        |> ...
String
-> (expectedFieldOrder -> totalFieldCount)
-> Decoder fieldValue
-> Decoder
{ expectedFieldOrder : totalFieldCount -> nextValidator
, gotFieldOrder : expectedFieldOrder -> Bool
, recordType : fieldValue -> nextConstructor
, totalFieldCount : totalFieldCount
}
-> Decoder
{ expectedFieldOrder : nextValidator
, gotFieldOrder : expectedFieldOrder -> Bool
, recordType : nextConstructor
, totalFieldCount : OnePlus totalFieldCount
}

Add a field to a record decoder.

import Json.Decode
import Json.Decode.Safe exposing (record, field)


userDecoder =
    record userConstructor userConstructor
        |> field "firstName" .firstName Json.Decode.string
        |> field "lastName" .lastName Json.Decode.string
        |> field "pets" .pets Json.Decode.int
        |> ...
Decoder
{ recordType : recordType
, expectedFieldOrder : expectedFieldOrder
, gotFieldOrder : expectedFieldOrder -> Bool
, totalFieldCount : totalFieldCount
}
-> Decoder recordType

Finalise the definition of a record decoder.

import Json.Decode
import Json.Decode.Safe exposing (endRecord, field, record)


userDecoder =
    record userConstructor userConstructor
        |> field "firstName" .firstName Json.Decode.string
        |> field "lastName" .lastName Json.Decode.string
        |> field "pets" .pets Json.Decode.int
        |> endRecord