2017-10-11 69 views
2

如何在Test API模塊中的Cmd msg上進行模式匹配?如何在Test 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", 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 } 

回答

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 
+0

是啊..這就是我終於實現了。 –

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