Skip to content

Commit ae08515

Browse files
committed
Add App example.
1 parent 11554dc commit ae08515

File tree

2 files changed

+57
-2
lines changed

2 files changed

+57
-2
lines changed

example/App.purs

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
module Example.App where
2+
3+
import Prelude
4+
import Control.Monad.Reader (ReaderT, asks, runReaderT)
5+
import Control.Monad.Reader.Class (class MonadAsk)
6+
import Data.Either (Either(..))
7+
import Effect (Effect)
8+
import Effect.Class (class MonadEffect, liftEffect)
9+
import Effect.Console (log)
10+
import Node.Process (getEnv)
11+
import Type.Data.Row (RProxy(..))
12+
import Type.Equality (class TypeEquals, from)
13+
import TypedEnv (Resolved, Variable, envErrorMessage)
14+
import TypedEnv (fromEnv) as TypedEnv
15+
16+
type Config f =
17+
( alertEmail :: f "ALERT_EMAIL" String
18+
, alertSubject :: f "ALERT_SUBJECT" String
19+
)
20+
21+
type ResolvedConfig = Record (Config Resolved)
22+
23+
newtype AppM a = AppM (ReaderT ResolvedConfig Effect a)
24+
25+
runAppM :: ResolvedConfig -> AppM ~> Effect
26+
runAppM env (AppM m) = runReaderT m env
27+
28+
derive newtype instance functorAppM :: Functor AppM
29+
derive newtype instance applyAppM :: Apply AppM
30+
derive newtype instance applicativeAppM :: Applicative AppM
31+
derive newtype instance bindAppM :: Bind AppM
32+
derive newtype instance monadAppM :: Monad AppM
33+
derive newtype instance monadEffectAppM :: MonadEffect AppM
34+
35+
instance monadAskAppM :: TypeEquals e ResolvedConfig => MonadAsk e AppM where
36+
ask = AppM $ asks from
37+
38+
main :: Effect Unit
39+
main = do
40+
eitherConfig <- TypedEnv.fromEnv (RProxy :: RProxy (Config Variable)) <$> getEnv
41+
case eitherConfig of
42+
Left error ->
43+
log $ "ERROR: " <> envErrorMessage error
44+
Right config ->
45+
runAppM config sendAlert
46+
47+
sendAlert :: AppM Unit
48+
sendAlert = do
49+
email <- asks _.alertEmail
50+
subject <- asks _.alertSubject
51+
liftEffect $ log ("Sending alert with subject \"" <> subject <> "\" to \"" <> email <> "\"...done.")

src/TypedEnv.purs

+6-2
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,11 @@ module TypedEnv
77
, type (<:)
88
, EnvError(..)
99
, envErrorMessage
10-
, class ReadValue
11-
, readValue
10+
, Resolved
1211
, class ParseValue
1312
, parseValue
13+
, class ReadValue
14+
, readValue
1415
, class ReadEnv
1516
, readEnv
1617
, class ReadEnvFields
@@ -64,6 +65,9 @@ envErrorMessage = case _ of
6465
EnvLookupError var -> "The required variable \"" <> var <> "\" was not specified."
6566
EnvParseError var -> "The variable \"" <> var <> "\" was formatted incorrectly."
6667

68+
-- | Useful for a type alias representing a resolved environment
69+
type Resolved (name :: Symbol) ty = ty
70+
6771
-- | Parses a `String` value to the specified type.
6872
class ParseValue ty where
6973
parseValue :: String -> Maybe ty

0 commit comments

Comments
 (0)