Elm 如何在测试API模块内的Cmd msg上进行模式匹配?
如何在测试API模块内的Cmd msg上进行模式匹配 我有一个测试API作为web服务的替代品Elm 如何在测试API模块内的Cmd msg上进行模式匹配?,elm,Elm,如何在测试API模块内的Cmd msg上进行模式匹配 我有一个测试API作为web服务的替代品 sources : Id -> (Result Http.Error (List Source) -> msg) -> Cmd msg sources profileId msg = [ { platform = "WordPress", username = "bizmonger", linksFound = 0 } , { platform = "YouTube"
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
Ok sources->^^^^^^^^^^^^模式与类型匹配:
Result error value
但它实际上要匹配的值是:
Cmd msg
注意:
type alias Source =
{ platform : String, username : String, linksFound : Int }
我知道这些函数返回Cmd-msg,我需要在Cmd-msg上进行模式匹配。但是,此代码位于TestAPI模块中,而不是典型的UI模块。因此,我认为我不必为依赖此TestAPI模块的UI客户端中已经定义的各种消息定义有区别的联合
附录:
type alias Source =
{ platform : String, username : String, linksFound : Int }
因为这是关于“模拟”API端点的,所以我将避免使用通常的“如果没有触发副作用,就不要在命令中装箱数据”spiel
相反,让我建议拆分源
函数:
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
我意识到我还在做函数式编程。 因此,为什么不从核心要素到更复杂的功能组合在一起呢 因此,我做了以下工作:
addSourceBase : Id -> Source -> List Source
addSourceBase profileId source =
source :: (profileId |> sourcesBase)
addSource : Id -> Source -> (Result Http.Error (List Source) -> msg) -> Cmd msg
addSource profileId source msg =
source
|> addSourceBase profileId
|> Result.Ok
|> msg
|> Task.succeed
|> Task.perform identity
赞成。。这就是我最后做的。