elm-pages-v3-beta/examples/pokedex/app/Effect.elm

101 lines
2.2 KiB
Elm
Raw Normal View History

2022-03-29 01:11:07 +03:00
module Effect exposing (Effect(..), batch, fromCmd, map, none, perform)
import Browser.Navigation
import Http
import Json.Decode as Decode
2022-04-04 19:40:37 +03:00
import Url exposing (Url)
2022-03-29 01:11:07 +03:00
type Effect msg
= None
| Cmd (Cmd msg)
| Batch (List (Effect msg))
| GetStargazers (Result Http.Error Int -> msg)
2022-04-04 19:40:37 +03:00
| FetchPageData
{ body : Maybe { contentType : String, body : String }
, path : Maybe String
, toMsg : Result Http.Error Url -> msg
}
type alias RequestInfo =
{ contentType : String
, body : String
}
2022-03-29 01:11:07 +03:00
none : Effect msg
none =
None
batch : List (Effect msg) -> Effect msg
batch =
Batch
fromCmd : Cmd msg -> Effect msg
fromCmd =
Cmd
map : (a -> b) -> Effect a -> Effect b
map fn effect =
case effect of
None ->
None
Cmd cmd ->
Cmd (Cmd.map fn cmd)
Batch list ->
Batch (List.map (map fn) list)
GetStargazers toMsg ->
GetStargazers (toMsg >> fn)
2022-04-04 19:40:37 +03:00
FetchPageData fetchInfo ->
FetchPageData
{ body = fetchInfo.body
, path = fetchInfo.path
, toMsg = fetchInfo.toMsg >> fn
}
2022-03-29 01:11:07 +03:00
2022-04-04 19:40:37 +03:00
perform :
{ fetchRouteData :
{ body : Maybe { contentType : String, body : String }
, path : Maybe String
, toMsg : Result Http.Error Url -> pageMsg
}
-> Cmd msg
}
-> (pageMsg -> msg)
-> Browser.Navigation.Key
-> Effect pageMsg
-> Cmd msg
perform info fromPageMsg key effect =
2022-03-29 01:11:07 +03:00
case effect of
None ->
Cmd.none
Cmd cmd ->
Cmd.map fromPageMsg cmd
Batch list ->
2022-04-04 19:40:37 +03:00
Cmd.batch (List.map (perform info fromPageMsg key) list)
2022-03-29 01:11:07 +03:00
GetStargazers toMsg ->
Http.get
{ url =
"https://api.github.com/repos/dillonkearns/elm-pages"
, expect = Http.expectJson (toMsg >> fromPageMsg) (Decode.field "stargazers_count" Decode.int)
}
2022-04-04 19:40:37 +03:00
FetchPageData fetchInfo ->
info.fetchRouteData
{ body = fetchInfo.body
, path = fetchInfo.path
, toMsg = fetchInfo.toMsg
}