What is TSRPC

TSRPC is a TypeScript RPC framework suitable for browser Web applications, WebSocket real-time applications, NodeJS microservices and other scenarios.

GitHub:github.com/k8w/tsrpc Chinese document: TSRPC. Cn video tutorial: www.bilibili.com/video/BV1hM…

Currently, most projects still use traditional Restful apis for back and forth communication, which has some pain points.

  1. Protocol definition depends on documents, and front-end and back-end tuning is often plagued by low-level errors (such as incorrect capitalization of field names and incorrect field types).
  2. Some frameworks implement protocol definition specifications but require the introduction of decorators or third-party IDL languages.
  3. Some frameworks implement Type validation but do not support TypeScript’s advanced types, such as the common Union Type in business:
// User information
interface UserInfo {
  // Source channel
  from: { type: 'Old User Invitation'.fromUserId: string }
    | { type: 'Promotional links'.url: string }
    | { type: 'Straight in' },
  // Register time
  createTime: Date
}
Copy the code
  1. JSON supports limited types, such as noneArrayBuffer, the implementation of file upload can be very troublesome.
  2. The request and response are plaintext, the threshold for cracking is too low, and the string encryption is limited and not strong enough.
  3. And so on…

We couldn’t find an off-the-shelf framework that perfectly solved these problems, so we redesigned and created TSRPC.

An overview of

A protocol called Hello, defined, implemented, and invoked by the browser.

Protocol definition

Define the protocol directly using type or interface, without the need for decorators and third-party IDL languages.

export interface ReqHello {
  name: string;
}

export interface ResHello {
  reply: string;
}
Copy the code

Server-side implementation

Runtime automatic verification of type, request parameters certain type safety.

import { ApiCall } from "tsrpc";

export async function ApiHello(call: ApiCall<ReqHello, ResHello>) {
  call.succ({
    reply: 'Hello, ' + call.req.name
  });
}
Copy the code

Client call

Reuse of protocol definitions across projects, code prompts throughout, no interface documentation required.

let ret = await client.callApi('Hello', {
    name: 'World'
});
console.log(ret); // { isSucc: true, res: { reply: 'Hello, World' } }
Copy the code

features

TSRPC has some of the most powerful features you’ve ever had, bringing you the ultimate development experience.

  • 🥤 Original TypeScript
    • Directly based on TypeScripttypeinterfaceDefine the agreement
    • No additional comments, no decorators, no third-party IDL languages
  • 👓 Automatic type checking
    • Input and output type checking is performed automatically at compile time and run time
    • Always type safe, feel free to write business code
  • 💾 Binary serialization
    • Smaller transfer volume than JSON
    • More data types than JSON: for exampleDate.ArrayBuffer.Uint8Array
    • Easy to implement binary encryption
  • 🔥 The most powerful TypeScript serialization algorithm ever
    • Implements serialization of type definitions in TypeScript source code without any annotations
    • The first and only binary serialization algorithm to support TypeScript advanced types includes:
      • Union Type
      • Intersection Type
      • Pick Type
      • Partial Type
      • Indexed Access Types
      • , etc.
  • multi-protocol
    • Also supports HTTP/WebSocket
  • 💻 Multiple platforms
    • NodeJS/browser/App/applets
  • ⚡ ️A high performance
    • Single-core single-process 5000+ QPS throughput (tested on Macbook Air M1, 2020)
    • Unit testing, stress testing, DevOps solutions
    • After several tens of millions of user level project verification

compatibility

It is perfectly possible to use TSRPC on the Server side while compatible with the traditional front-end.

  • Compatible with Restful API calls in JSON format
    • Self-useXMLHttpRequest,fetchOr other AJAX frameworks that invoke the interface as JSON
  • Compatible with pure JavaScript for project use
    • You can use the TSRPC Client in a pure JavaScript project and also enjoy type checking and serialization features
  • Compatible with Internet Explorer 10
    • Browser compatible with IE 10, Chrome 30

Implementation principle of runtime type detection

It is well known that TypeScript type detection only happens at compile time because type information (such as type and interface) is erased at compile time. How can TSRPC detect these erased types at run time? Besides, the TypeScript compiler is several megabytes in size while TSRPC is tens of KB…

In fact, this is because we follow the TypeScript type system and implement a lightweight type system independently, which can do type detection and even binary serialization at runtime. It supports most common TypeScript types.

A list of supported types

Try to fit

Using the create-tsrpc-app tool, you can quickly create TSRPC projects.

npx create-tsrpc-app@latest
Copy the code

The creation process is interactive, and it is easy to create a TSRPC full stack application project that contains the front and back ends by selecting the appropriate configuration from the menu.

If you choose to create an HTTP short connection service, a demo message board project will be created. If you select the WebSocket Long Connection service, a demo project of a live chat room is created.

The resources

GitHub:github.com/k8w/tsrpc Chinese document: TSRPC. Cn video tutorial: www.bilibili.com/video/BV1hM…