Skip to content

Instantly share code, notes, and snippets.

Embed
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. https://github.com/expressjs/body-parser#readme
There are many more options, but I've written binding to just the one I needed: https://github.com/expressjs/body-parser#bodyparserjsonoptions
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: https://bucklescript.github.io/docs/en/object-deprecated#typing
You are recommended to use `@bs.deriving` instead. https://bucklescript.github.io/docs/en/object#record-mode
*/
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: https://github.com/expressjs/morgan#combined */
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)
}
);
App.post(app, ~path="/myApp", apply(myJsonHandler));
let onListen = (port, e) =>
switch (e) {
| exception (Js.Exn.Error(e)) =>
Js.log(e);
Node.Process.exit(1);
| _ =>
Js.log @@
"myApp listening at http://127.0.0.1:"
++ 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