Body Parser

Like Express, body-parser is a function to parse the body of an incoming request.

By default, Teasim will parse the body with content-type of:

  • text/plain
  • application/json
  • multipart/form-data
  • application/x-www-form-urlencoded

And assign the value to Context.body.

Then you can get body from body as:

import { Teasim } from "teasim";

new Teasim()
  .post("/add", ({ body }) => {
    console.log(body);
  })
  .listen(8080);

Custom body parser

If you want to support more content-types, you can use the onParse method:

new Teasim().onParse(({ request }, contentType) => {
  if (contentType === "application/custom-type") return request.text();
});

The returned value will be assigned to Context.body. If not, Teasim will continue iterating through additional parser functions assigned by onParse until either body is assigned or all parsers have been executed.

You can also use request to add custom parsing behavior.

For example, parsing GraphQL on a specific path:

app.onParse(({ request }, contentType) => {
  if (path === getPath(request.url) && contentType === "application/json") return request.text();
});
ON THIS PAGE