Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A simple bs-express demo with a few custom bindings
/* This example demonstrates how to use bs-express to receive a Json POST request and emit a Json response. */
let myJsonHandler = incoming =>
/* This is the application-level request handler. It is a pure function that takes a string and returns a Json.
In this example, Express doesn't parse the incoming string. We leave it to the application handler so that it has
more control (deal with parsing errors in its own way for example)
incoming |> Json.parseOrRaise |> MyApplication.doSomething;
open Express;
/* This is a direct binding to Express's parser middlewares.
There are many more options, but I've written binding to just the one I needed:
Please note the "." in the type definition - it is a "Javascript object" and not a plain Reason record.
In this example I'm using a deprecated format. See:
You are recommended to use `@bs.deriving` instead.
type bodyParserOptions = {. "limit": int};
[@bs.module "body-parser"]
external bodyParserText : bodyParserOptions => Express.Middleware.t = "text";
/* Create a binding for a `morgan` function that takes just a string and returns a middleware */
[@bs.module] external morgan : string => Express.Middleware.t = "morgan";
/* Bindings are done. Begin application! */
let app = express();
/* Use Morgan for logging; emit in Apache's log format: */
App.use(app, morgan("combined"));
/* 5 mb max upload size for now */
App.use(app, bodyParserText({"limit": 1024 * 1024 * 5}));
let apply = f =>
Middleware.from((req, res, next) =>
switch (Request.bodyText(req)) {
| Some(data) =>
let response = f(data);
Response.sendJson(res, response);
| None => next(Next.route)
);, ~path="/myApp", apply(myJsonHandler));
let onListen = (port, e) =>
switch (e) {
| exception (Js.Exn.Error(e)) =>
| _ =>
Js.log @@
"myApp listening at"
++ string_of_int(port)
let port = 3488;
App.listen(app, ~port, ~onListen=onListen(port), ());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment