如何在Test API模块中对Cmd msg进行模式匹配?
我有一个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
Ok来源 - > ^^^^^^^^^^模式匹配类型的东西:
Result error value
但它实际上要匹配的值是:
Cmd msg
注意:
据我所知,这些函数返回一个Cmd msg,我需要在Cmd msg上进行模式匹配。但是,此代码位于TestAPI模块中,而不是典型的UI模块。因此,我认为我不应该为依赖于此TestAPI模块的UI客户端中已定义的各种消息定义一个有区别的联合。
附录
type alias Source =
{ platform : String, username : String, linksFound : Int }
答案 0 :(得分:4)
因为这是关于"嘲笑"一个API端点,如果你没有触发副作用,我会在命令中不要使用我常用的数据盒数据"高谈阔论。
相反,让我建议拆分您的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
答案 1 :(得分:1)
我意识到我还在进行函数式编程。 因此,为什么不从核心要素到更多参与者一起组成功能。
因此,我做了以下事情:
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