Package

purescript-nodetrout

Repository
nsaunders/purescript-nodetrout
License
MIT
Uploaded by
nsaunders
Published on
2019-11-25

Build a Node HTTP server with Trout.

purescript-nodetrout

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.

An API in 4 simple steps

  1. 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)
  1. Create a Proxy value to capture the route specifications:
site :: Proxy Site
site = Proxy
  1. 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) } }
  1. 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..."

Installation

bower:

bower install --save purescript-nodetrout

psc-package:

psc-package install nodetrout

spago:

spago install nodetrout

Examples

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 + pulp:

bower install
pulp run -I example -m Example.<example-name>

spago:

spago run -p example/<example-name>.purs -m Example.<example-name>