API.elm 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. module API exposing (getDraft, getDrafts, getSetData, getSets)
  2. import Database exposing (Database)
  3. import DraftMeta exposing (DraftMeta)
  4. import Http
  5. import Json.Decode as Decode
  6. import Url.Builder as UrlB
  7. apiUrl : String
  8. apiUrl =
  9. "http://localhost:8000"
  10. makeApiUrl : List String -> String
  11. makeApiUrl paths =
  12. apiUrl ++ "/" ++ String.join "/" paths
  13. getSets : (Result String (List String) -> msg) -> Cmd msg
  14. getSets onSuccess =
  15. Http.get
  16. { url = makeApiUrl [ "sets" ]
  17. , expect =
  18. Http.expectJson (Result.mapError httpErrorToString >> onSuccess)
  19. (Decode.field "sets"
  20. (Decode.list Decode.string)
  21. )
  22. }
  23. getSetData : String -> (Result String ( String, Maybe Database ) -> msg) -> Cmd msg
  24. getSetData setCode onSuccess =
  25. Http.request
  26. { method = "GET"
  27. , headers = []
  28. , url = makeApiUrl [ "sets", setCode ]
  29. , body = Http.emptyBody
  30. , expect = Http.expectJson (Result.mapError httpErrorToString >> onSuccess) Database.decoder
  31. , timeout = Nothing
  32. , tracker = Just setCode
  33. }
  34. getDrafts : String -> (Result String (List DraftMeta) -> msg) -> Cmd msg
  35. getDrafts historyUrl onSuccess =
  36. Http.get
  37. { url = apiUrl ++ UrlB.absolute [ "drafts" ] [ UrlB.string "history" historyUrl ]
  38. , expect =
  39. Http.expectJson (Result.mapError httpErrorToString >> onSuccess)
  40. (Decode.field "drafts"
  41. (Decode.list DraftMeta.decoder)
  42. )
  43. }
  44. getDraft : String -> (Result String DraftMeta -> msg) -> Cmd msg
  45. getDraft draftID onSuccess =
  46. Http.get
  47. { url = "https://www.17lands.com" ++ UrlB.absolute [ "data", "draft" ] [ UrlB.string "draft_id" draftID ]
  48. , expect =
  49. Http.expectJson (Result.mapError httpErrorToString >> onSuccess) DraftMeta.decoder
  50. }
  51. httpErrorToString : Http.Error -> String
  52. httpErrorToString error =
  53. case error of
  54. Http.BadUrl url ->
  55. "Bad URL: " ++ url
  56. Http.Timeout ->
  57. "Timeout"
  58. Http.NetworkError ->
  59. "Network error"
  60. Http.BadStatus status ->
  61. "Bad status: " ++ String.fromInt status
  62. Http.BadBody body ->
  63. "Bad body: " ++ body