Skip to main content

Start with HTTP Server

After creating a server in Getting Started, Farrow also can do more complex thing with another APIs as a HTTP Server.

Farrow middleware is an improvement based on the traditional middleware. Only requestInfo object and next function are in parameters, Response info is represeted by return value, a object created by Response object in farrow.

http.use((requestInfo, next) => {
return Response.text("Hello Farrow");
});

And the requestInfo object is not Node.js http.IncomingMessage, but only contains the raw information extracted from Node.js http.IncomingMessage.

So it can be used like this.

http.use(({ pathname }, next) => {
return Response.text(`Hello Farrow with path: ${pathname}`);
});

As you saw, the response information is set by returning Response object. In addition to set the response body with text, the json, file... alse can set the body with another format.

http.use(({ pathname }, next) => {
return Response.json({
message: "Hello Farrow",
pathname,
});
});

And the status and headers, cookies of response alse can be set with Response object.


Farrow also has Routing system, In addition to add middleware by http.use, Farrow also support use http.METHOD() to constraint the service the particular endpoint by METHOD function, path of URL and Schema of Content.

http
// constraint to `post` method, `/addTodo` path and with body like { content: string }
.post("/addTodo", { body: { content: String } })
.use(({ body: { content } }) => {
// ...

return Response.json({
code: 1,
message: "success",
});
});

If you do not you to constraint the method, http.match is the better choice.

http
.match({ pathname: "/addTodo", body: { content: String } })
.use(({ body: { content } }) => {
// ...

return Response.json({
code: 1,
message: "success",
});
});

Farrow has provided the Router to support grouping api handling.

import { Http, Router, Response } from "farrow-http";

const todo = Router();

todo.get("/list").use(/** */);
todo.post("/add").use(/** */);
todo.put("/clear").use(/** */);

const http = Http();

http.route("/todo").use(todo);
info

If you want to know more detail about Farrow HTTP Server, see HTTP Server.

If you want to know the design philosophy about Farrow HTTP Server, see Why new middleware mode and Why Schema Builder Based on TypeScript.

Using Farrow in other HTTP Server is very easy. In Express, you can add Farrow app by adapter.

const http = Http();

http
.match({
pathname: "/test",
})
.use((data) => {
return Response.text(JSON.stringify(data));
});

const app = express();

app.use("/farrow", adapter(http));
info

For now, Farrow has support Express, Koa. See more at farrow-express, farrow-koa.