Skip to content

Instantly share code, notes, and snippets.

@darui00kara
Last active April 10, 2022 13:56
Show Gist options
  • Save darui00kara/4807ba01d16c8c1e7205b15ded2fe7f0 to your computer and use it in GitHub Desktop.
Save darui00kara/4807ba01d16c8c1e7205b15ded2fe7f0 to your computer and use it in GitHub Desktop.
Elm json encode example
-- おまけ用のメモ
> body = Http.jsonBody (UserEncoder.user User.new)
StringBody "application/json" "{\"id\":0,\"name\":\"\",\"email\":\"\"}"
: Http.Body
> import Model.UserDecoder as UserDecoder
> Http.post "http://localhost:4000/exmamples" body UserDecoder.user
Request { method = "POST", headers = [], url = "http://localhost:4000/exmamples", body = StringBody "application/json" "{\"id\":0,\"name\":\"\",\"email\":\"\"}", expect = { responseType = "text", responseToResult = <function> }, timeout = Nothing, withCredentials = False }
: Http.Request Model.User.Schema
> Http.post "http://localhost:4000/exmamples" body
<function> : Json.Decode.Decoder a -> Http.Request a
$ elm repl
> import Model.User as User
> import Model.UserEncoder as UserEncodeer
> import Http
> UserEncodeer.user User.new |> Http.jsonBody
StringBody "application/json" "{\"id\":0,\"name\":\"\",\"email\":\"\"}"
: Http.Body
module Model.User exposing (Schema, new)
type alias Schema =
{ id : Int
, name : String
, email : String
}
new : Schema
new =
Schema 0 "" ""
module Model.UserEncoder exposing (user)
import Json.Encode as Encode exposing (Value, int, string, object)
import Model.User as User
id : Int -> (String, Encode.Value)
id value =
("id", Encode.int value)
name : String -> (String, Encode.Value)
name value =
("name", Encode.string value)
email : String -> (String, Encode.Value)
email value =
("email", Encode.string value)
user : User.Schema -> Encode.Value
user schema =
Encode.object
[ id schema.id
, name schema.name
, email schema.email
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment