Created
June 3, 2019 05:03
-
-
Save miyamoen/5337337a27710d742d96f95bcbd7bcc4 to your computer and use it in GitHub Desktop.
きみたけのStatus型を作ろう🐏🐏
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Status exposing | |
( Status(..) | |
, map, fromHttpResult | |
, WithStatus | |
, initWithStatus, setLoading, updateWithStatus | |
) | |
{-| | |
## Status | |
@docs Status | |
@docs map, fromHttpResult | |
## WithStatus | |
@docs WithStatus | |
@docs initWithStatus, setLoading, updateWithStatus | |
-} | |
import Http | |
-------------------------------- Status -------------------------------- | |
type Status a | |
= NotAsked | |
| Loading | |
| Failure Http.Error | |
| Success a | |
{-| Statusの型変換 | |
-} | |
map : (a -> b) -> Status a -> Status b | |
map tagger status = | |
case status of | |
Success a -> | |
Success (tagger a) | |
NotAsked -> | |
NotAsked | |
Loading -> | |
Loading | |
Failure err -> | |
Failure err | |
{-| StatusをHttpの結果から作る | |
expect = | |
expectJson fromHttpResult decoder | |
-} | |
fromHttpResult : Result Http.Error a -> Status a | |
fromHttpResult result = | |
case result of | |
Ok data -> | |
Success data | |
Err err -> | |
Failure err | |
-------------------------------- WithStatus -------------------------------- | |
type alias WithStatus a = | |
{ status : Status () | |
, data : a | |
} | |
{-| 初期化 | |
initWithStatus Hoge.init | |
-} | |
initWithStatus : a -> WithStatus a | |
initWithStatus a = | |
WithStatus NotAsked a | |
{-| apiを叩くときにLoading状態にする | |
-} | |
setLoading : WithStatus a -> WithStatus a | |
setLoading { data } = | |
WithStatus Loading data | |
{-| Apiでとってきた`Status new`でModelに入っている`WithStatus data`を更新する | |
updateWithStatus (\new data -> Hoge.update new data) status hoge | |
-} | |
updateWithStatus : (new -> data -> data) -> Status new -> WithStatus data -> WithStatus data | |
updateWithStatus f status data = | |
let | |
status_ = | |
map (always ()) status | |
in | |
case status of | |
Success new -> | |
WithStatus status_ (f new data.data) | |
_ -> | |
WithStatus status_ data.data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment