在Elm中序列Http.get

Tha*_*you 4 elm elm-architecture

下面我有一个button试图加载远程内容...

import Post exposing (Post)
import Html exposing (..)
import Html.Events exposing (..)
import Http
import Json.Decode as Decode


type alias Model =
    { posts : List Post }


type Msg
    = Search String
    | PostsReceived (Result Http.Error (List Post))


update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        Search s ->
            let
                cmd =
                    (Decode.list Post.decode)
                        |> Http.get ("/posts?author=" ++ s)
                        |> Http.send PostsReceived
            in
                ( model, cmd )

        PostsReceived (Ok posts) ->
            { model | posts = posts }
                ! []

        PostsReceived (Err error) ->
            ( model, Cmd.none )


view : Model -> Html Msg
view model =
    button
        [ onClick (Search "amelia") ]
        [ text "Read posts by Amelia" ]
Run Code Online (Sandbox Code Playgroud)

这是一个有效的Elm程序,只有一个小问题:API不允许我按字符串搜索.这是容许

/posts?author=amelia  => Malformed Request Error
Run Code Online (Sandbox Code Playgroud)

但是,这允许的

/posts?author=2       => [ {...}, {...}, ... ]
Run Code Online (Sandbox Code Playgroud)

所以我必须首先找一个作者来获取他/她id,然后我可以使用作者的id获取帖子...

/author?name=amelia => { id: 2, name: "amelia", ... }
/posts?author=2
Run Code Online (Sandbox Code Playgroud)

如何在下一个请求后对一个请求进行排序?理想情况下,我想将作者缓存在模型中的某个位置,因此我们只是请求我们之前没有见过的那些.

bdu*_*kes 5

您可以使用Task.andThen将两个任务链接在一起.假设/posts响应包含作者ID,则可以在处理响应时将该作者ID添加到模型中.

    Search s ->
        let
            getAuthor =
                Author.decode
                    |> Http.get ("/author?name=" ++ s)
                    |> Http.toTask
            getPosts author =
                (Decode.list Post.decode)
                    |> Http.get ("/posts?author=" ++ author.id)
                    |> Http.toTask
            cmd =
                getAuthor
                    |> Task.andThen getPosts
                    |> Task.attempt PostsReceived
        in
            ( model, cmd )
Run Code Online (Sandbox Code Playgroud)

我有这个编译在https://ellie-app.com/DBJc6Kn3G6a1,如果这有帮助