This repository has been archived by the owner on Aug 5, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Monad.hs
70 lines (55 loc) · 1.7 KB
/
Monad.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Web.Zenfolio.Monad (
ZM,
zenfolio,
liftIO,
getToken,
withToken,
getDebug,
withDebug,
debug
) where
import Control.Monad (when)
import Control.Monad.Reader (MonadReader, ReaderT(..), asks, local)
import Control.Monad.Trans (MonadIO, liftIO)
import Network.JsonRpc (Remote(..), ioRemote_, JSON,
RpcEnv(rpcHeaders,rpcDebug), rpcEnv)
import Web.Zenfolio.RPC (zfTokenHeader)
import Web.Zenfolio.Types (AuthToken)
data ZMEnv = ZMEnv {
zmToken :: Maybe AuthToken,
zmDebug :: Bool
} deriving (Eq, Show)
newtype ZM a = ZM (ReaderT ZMEnv IO a)
deriving (Monad, MonadReader ZMEnv, MonadIO)
instance JSON a => Remote (ZM a) where
remote_ h f = do
token <- getToken
dbg <- getDebug
liftIO $ do
let env = rpcEnv {
rpcHeaders = headers token,
rpcDebug = dbg
}
ioRemote_ h f env
where headers Nothing = []
headers (Just token) = [ zfTokenHeader token ]
zenfolio :: ZM a -> IO a
zenfolio (ZM zm) = runReaderT zm nullEnv
nullEnv :: ZMEnv
nullEnv = ZMEnv {
zmToken = Nothing,
zmDebug = False
}
getToken :: ZM (Maybe AuthToken)
getToken = asks zmToken
withToken :: AuthToken -> ZM a -> ZM a
withToken token zm = local addToken zm
where addToken env = env { zmToken = Just token }
getDebug :: ZM Bool
getDebug = asks zmDebug
withDebug :: Bool -> ZM a -> ZM a
withDebug dbg zm = local setDebug zm
where setDebug env = env { zmDebug = dbg }
debug :: String -> ZM ()
debug msg = getDebug >>= \d -> when d (liftIO $ putStrLn msg)