Skip to content

Latest commit

 

History

History
88 lines (62 loc) · 2.59 KB

README.md

File metadata and controls

88 lines (62 loc) · 2.59 KB

Cuple RPC

REST-compatible RPC for typescript services

It's designed with compatibility in mind with external services but also keeping the advantages of tightly coupled microservices. For example, a Java microservice can also send requests as usual. It's REST first, so it typechecks HTTP headers, URL parameters, query strings, as well, not just the bodies. Unlike trpc, it also tracks error responses, and even lets you return custom validation errors. It tries to be out of the way as much as possbile, and lets you do everything that is possbile with express.

Example

example.mp4

Open in StackBlitz

About RPCs in general

RPC stands for Remote Procedure Call. You define procedures in the server, and you call them from the client. Let it be either backend-backend communication or backend-frontend. RPC usually indicates strict typing of procedures for maximal compatibility and tight coupling.

Installation

Please check the docs.

Or try the boilerplate: https://github.com/fxdave/react-express-cuple-boilerplate

Examples: ./test/src/examples
Tests: ./test/src

Example Server

const builder = createBuilder(expressApp);

export const routes = {
  getPost: builder
    .path("/post/:id") // optional for REST compatibility
    .paramsSchema(
      z.object({
        id: z.coerce.number(),
      }),
    )
    .get(async ({ data }) => {
      const post = await getPost(data.params.id);

      if (!post)
        return notFoundError({
          message: "Post is not found",
        });

      return success({
        post,
      });
    }),
};

initRpc(expressApp, {
  path: "/rpc",
  routes,
});

Example Client

const client = createClient<typeof routes>({
  path: "http://localhost:8080/rpc",
});

async function getPost(id: number) {
  const response = await client.getPosts.get({ params: { id } });

  console.log(postsResponse.post); // type error

  if (response.result === "success") {
    console.log(postsResponse.post); // no type error
  }
}

Companies using Cuple

RolloutIt

Resources

Boilerplate: https://github.com/fxdave/react-express-cuple-boilerplate
Docs: https://fxdave.github.io/cuple/
Examples: ./test/src/examples
Tests: ./test/src