Twirp-TS

2.5.0 · active · verified Tue Apr 21

Twirp-TS is a comprehensive TypeScript implementation of the Twirp RPC specification (v7 and v8), designed for generating both server and client code from Protocol Buffer definitions. It operates as a plugin for `protoc`, relying on either `@protobuf-ts/plugin` or `ts-proto` for the underlying protobuf message generation. The library facilitates building performant, type-safe APIs with minimal boilerplate, offering features like automatic OpenAPI V3 spec generation, server-side hooks and interceptors, and a gateway for proxying requests. It is actively maintained, with the current stable version being 2.5.0, and receives regular updates to fix bugs and introduce new generation options, such as granular client/server-only code generation. Its primary differentiator lies in providing a full-stack TypeScript solution for Twirp, ensuring strong type consistency from schema to implementation.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a basic Twirp server using Express, implementing a `Haberdasher` service with a `MakeHat` method. It shows error handling and listening on a specified port.

import * as http from "http";
import { TwirpContext, TwirpError, TwirpErrorCode } from "twirp-ts";
// Assuming these are generated from your .proto file, e.g., 'haberdasher.proto'
import { createHaberdasherServer } from "./generated/haberdasher.twirp";
import { Hat, Size, Haberdasher } from "./generated/service";

// Implement the Haberdasher service according to the generated interface
const haberdasherService: Haberdasher = {
  async makeHat(ctx: TwirpContext, size: Size): Promise<Hat> {
    // Validate input
    if (size.inches <= 0) {
      throw new TwirpError(TwirpErrorCode.InvalidArgument, "size.inches must be positive");
    }

    console.log(`Received request for hat of size: ${size.inches} inches`);
    // Simulate work and return a hat
    return {
      inches: size.inches,
      color: "blue",
      name: "fedora"
    };
  }
};

// Create the Twirp server instance
const twirpServer = createHaberdasherServer(haberdasherService);

// Create a standard Node.js HTTP server and mount the Twirp handler
const server = http.createServer(twirpServer.httpHandler());

const PORT = process.env.PORT || 8080;
server.listen(PORT, () => {
  console.log(`Twirp Haberdasher server listening on port ${PORT}`);
  console.log("To test: curl -d '{\"inches\":12}' -H \"Content-Type: application/json\" http://localhost:8080/twirp/haberdasher.Haberdasher/MakeHat");
});

view raw JSON →