如何在测试API模块内的Cmd消息上进行模式匹配?

我有一个Test API,可以替代Web服务。

sources : Id -> (Result Http.Error (List Source) -> msg) -> Cmd msg
sources profileId msg =
    [ { platform = "WordPress", username = "bizmonger", linksFound = 0 }
    , { platform = "YouTube", username = "bizmonger", linksFound = 0 }
    , { platform = "StackOverflow", username = "scott-nimrod", linksFound = 0 }
    ]
        |> Result.Ok
        |> msg
        |> Task.succeed
        |> Task.perform identity


问题:

我收到以下代码的编译错误:

addSource : Id -> Source -> (Result Http.Error (List Source) -> msg) -> Cmd msg
addSource profileId source msg =
    let
        result =
            sources profileId msg
    in
        case result of
            Ok sources ->
                (source :: sources)
                    |> Result.Ok
                    |> msg
                    |> Task.succeed
                    |> Task.perform identity

            Err _ ->
                Cmd.none



好的源-> ^^^^^^^^^^^模式匹配类型的东西:

Result error value


但是它将实际尝试匹配的值是:

Cmd msg



注意:

我知道这些函数会返回一个Cmd消息,并且我需要在Cmd消息上进行模式匹配。但是,此代码在TestAPI模块中,而不是典型的UI模块中。因此,我认为我不必为依赖于此TestAPI模块的UI客户端中已定义的各种消息定义一个有区别的联合。

附录:

type alias Source =
    { platform : String, username : String, linksFound : Int }

最佳答案

由于这是关于“模拟” API端点的,因此,我将避免执行通常的“如果不触发副作用,则不要在命令中装箱数据” spiel。

相反,让我建议拆分您的sources函数:

sourceData : List Source
sourceData =
    [ { platform = "WordPress", username = "bizmonger", linksFound = 0 }
    , { platform = "YouTube", username = "bizmonger", linksFound = 0 }
    , { platform = "StackOverflow", username = "scott-nimrod", linksFound = 0 }
    ]


mockResponse : a -> (Result Http.Error a -> msg) -> Cmd msg
mockResponse data tagger =
    Result.Ok data
        |> Task.succeed
        |> Task.perform tagger


sources : Id -> (Result Http.Error (List Source) -> msg) -> Cmd msg
sources profileId msg =
    mockResponse sourceData msg


现在,实现您的addSource函数成为一个相当简单的调用,如下所示:

addSource : Id -> Source -> (Result Http.Error (List Source) -> msg) -> Cmd msg
addSource profileId source msg
    mockResponse (source :: sourceData) msg

07-28 07:47