Skip to main content

Start with RPC Server

Farrow also support the RPC-like server services. It focus on providing type friendly, validation for JSON value. It will service as the middleware of Farrow HTTP Server.

RPC

Before continuing the development, the packages(which support validation, code generation... by Farrow Schema) for Farrow RPC API need be installed.

yarn add farrow-schema farrow farrow-api farrow-api-server

Creating the Schema of greeting API.

import { Struct } from "farrow-schema";

// input schema
const GreetingInput = Struct({
name: String,
});

// output schema
const GreetingOutput = Struct({
greeting: String,
});

Construct the API with input schema, output schema and the calling handler.

import { Api } from "farrow-api";

const greeting = Api(
{
input: GreetingInput,
output: GreetingOutput,
},
(input) => {
const greeting = `Hello ${input.name}!`;
return { greeting };
}
);

Combine APIs into Service.

import { ApiService } from "farrow-api-server";

export const GreetingService = ApiService({
entries: {
greeting,
},
});

Add the service to HTTP Server.

http.route("/api/greeting").use(GreetingService);

For now, open Farrow Playground and connect the service.

Farrow Playground Connect

Select the greeting API.

Farrow Playground Select API

And send the input object.

{
"name": "foo"
}

Will get the response object.

{
"greeting": "foo"
}

You also can send the request with Postman. But the input shuold be:

{
"type": "Single",
"path": ["greeting"],
"input": {
"name": "foo"
}
}
info

If you want to know more detail about Farrow API, see RPC.

If you want to know the design philosophy about Farrow API, see Why RPC-like API and Why Schema Builder Based on TypeScript.

Code Generation

For better presentation, we need a SPA project. Using create-react-app.

yarn create react-app react-project --template typescript

Install farrow and farrow-api-client.

yarn add farrow-api-client
yarn add -D farrow

Creating farrow.config.js.

farrow.config.js
const { createFarrowConfig } = require("farrow");

module.exports = createFarrowConfig({
api: [
{
src: "http://localhost:3000/api/greeting",
dist: `${__dirname}/src/api/greeting.ts`,
},
],
});

Add farrow dev to start script in package.json, and run it. The calling code for client will be generated to /src/api/greeting.tsCall it in React Component.

import { api } from "./api/greeting";

// ...

useEffect(() => {
api.greeting({ name: "foo" }).then(({ greeting }) => {
console.log(greeting);
});
}, []);

Open the SPA page in browser, you will see the request and the consoled greeting message.

info

If you want to know more detail about Code generation of Farrow API, see Get code at Client.

If you want to know the design philosophy about Farrow API, see Why RPC-like API and Why Schema Builder Based on TypeScript.