Skip to content

Instantly share code, notes, and snippets.

@syossan27
Last active December 16, 2018 04:28
Show Gist options
  • Save syossan27/527e61e7c5e1c61265cf3f2db19bcd5c to your computer and use it in GitHub Desktop.
Save syossan27/527e61e7c5e1c61265cf3f2db19bcd5c to your computer and use it in GitHub Desktop.
---- UPDATE ----
type Msg
= NewActresses (Result Http.Error (List Actress))
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
-- リクエスト成功時処理
-- 戻り値であるnewactressがDecodeされたRecord
NewActresses (Ok newactresses) ->
( { model | actresses = newactresses, paginatedActresses = Paginate.fromList 40 newactresses }, Cmd.none )
-- リクエスト失敗時処理
NewActresses (Err _) ->
( { model | actresses = [], paginatedActresses = Paginate.fromList 40 [] }, Cmd.none )
---- HTTP ----
-- APIサーバから女優一覧JSONを取得する
url =
"https://example.com"
-- Actress(女優Model)を取得するためのリクエストを作成
requestActresses : Model -> Http.Request (List Actress)
requestActresses model =
let
-- URLクエリパラメータの付加処理
createQueryString : List String -> String
createQueryString searchParams =
url ++ "?params=" ++ String.join "," searchParams
-- 取得してきたJSONをデコードするためのDecoderを定義
actress : Decode.Decoder Actress
actress =
-- JSONのフィールドをElmのActress Recordのフィールドにマッピングする
-- https://package.elm-lang.org/packages/elm-lang/core/5.0.0/Json-Decode#succeed
-- https://package.elm-lang.org/packages/NoRedInk/elm-json-decode-pipeline/latest/
Decode.succeed Actress
|> required "name" string
|> required "image" string
|> optional "height" string "-"
|> optional "age" string "-"
|> optional "bust" string "-"
|> optional "cup" string "-"
|> optional "west" string "-"
|> optional "hip" string "-"
in
-- GETリクエスト時にURLにクエリパラメータを付加し、引数とする
-- https://package.elm-lang.org/packages/elm-lang/http/1.0.0/Http#get
Http.get (createQueryString model.searchParams) (Decode.list actress)
-- 作成したリクエストを送信する
-- https://package.elm-lang.org/packages/elm-lang/http/1.0.0/Http#send
getActresses : Model -> Cmd Msg
getActresses model =
Http.send NewActresses (requestActresses model)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment