Trout is a type-level routing DSL. Similar to Haskell's Servant library, Trout allows routes to be specified as a data type. Given this data type along with a record of corresponding handlers, this library can produce a node-http
request handler of type Request -> Response -> Effect Unit
, which can then be used to create an HTTP server.
- Specify routes as a data type. Here, we create a
GET /admin
route that requires a Basic Authorization header and responds with a greeting:
type Site = "admin" := "admin" :/ Header "Authorization" BasicAuth :> Resource (Get Greeting JSON)
- Create a
Proxy
value to capture the route specifications:
site :: Proxy Site
site = Proxy
- Define a handler for each route. Here, we greet the user by the username specified in the Basic Authorization header:
resources :: forall m. Monad m => { admin :: BasicAuth -> { "GET" :: ExceptT HTTPError m Greeting } }
resources = { admin: \auth -> { "GET": pure $ Greeting $ "Hello, " <> (fst $ un BasicAuth auth) } }
- Serve the API using
node-http
:
main :: Effect Unit
main = do
server <- createServer $ serve' site resources (const $ pure unit)
listen server { hostname: "0.0.0.0", port: 3000, backlog: Nothing } $ log "Listening on port 3000..."
bower install --save purescript-nodetrout
psc-package install nodetrout
spago install nodetrout
A number of usage examples are available here.
To run the examples, clone the repository and run one of the following depending on your package manager and build tool, replacing <example-name>
with the name of one of the examples.
bower install
pulp run -I example -m Example.<example-name>
spago run -p example/<example-name>.purs -m Example.<example-name>