purescript-httpurple/docs/Examples/CustomStack/Main.purs

55 lines
1.8 KiB
Haskell
Raw Normal View History

module Examples.CustomStack.Main where
import Prelude
import Control.Monad.Reader (class MonadAsk, ReaderT, asks, runReaderT)
2022-05-22 11:30:14 +00:00
import Data.Generic.Rep (class Generic)
import Data.Maybe (Maybe(..))
import Effect.Aff (Aff)
import Effect.Aff.Class (class MonadAff)
import Effect.Console (log)
import HTTPurple (Request, Response, ResponseM, ServerM, ok, serve)
2022-05-22 11:30:14 +00:00
import Routing.Duplex as RD
import Routing.Duplex.Generic as RG
data Route = SayHello
derive instance Generic Route _
route :: RD.RouteDuplex' Route
route = RD.root $ RG.sum
{ "SayHello": RG.noArgs
}
-- | A type to hold the environment for our ReaderT
type Env = { name :: String }
-- | A middleware that introduces a ReaderT
readerMiddleware ::
2022-05-22 11:30:14 +00:00
forall route.
(Request route -> ReaderT Env Aff Response) ->
Request route ->
ResponseM
readerMiddleware router request = do
runReaderT (router request) { name: "joe" }
-- | Say 'hello, joe' when run
2022-05-22 11:30:14 +00:00
sayHello :: forall m. MonadAff m => MonadAsk Env m => Request Route -> m Response
sayHello _ = do
name <- asks _.name
ok $ "hello, " <> name
-- | Boot up the server
main :: ServerM
main =
2022-08-24 17:59:06 +00:00
serve { hostname: "localhost", port: 8080, onStarted } { route, router: readerMiddleware sayHello }
where
onStarted = do
log " ┌───────────────────────────────────────┐"
log " │ Server now up on port 8080 │"
log " │ │"
log " │ To test, run: │"
log " │ > curl -v localhost:8080 │"
log " │ # => hello, joe │"
log " └───────────────────────────────────────┘"