|
| 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.") |
0 commit comments