An experimental library that implements a bidirectional Method+Event protocol for your homogenous Typescript code.
Here is a short example how it works:
// { server, client }
// Define a Method and an Event
const FindUser = Method.new("GetUser", t.string, t.type({ name: t.string, age: t.number }));
const NewUser = Event.new("NewUser", t.string);
// Implement a Method on the Server
server.onMethod(FindUser, name => { name: "Alice", age: 80000 });
server.onEvent(NewUser, name => console.log(`New user: ${name}`));
// Call it from the Client
const { name, age } = await (new FindUser("Alice").with(client));
new NewUser("Hashelq").with(client)What is interesting, that everything you have just seen can also be used backwards!
client.onMethod(FindUser, name => { name: "???", age: -1 });
client.onEvent(NewUser, name => console.log(`New user: ${name}`));
const { name, age } = await (new FindUser("Alice").withs(server, server.clients[0]));
new NewUser("HashElq").withs(client, server.clients[0]);src/tests.ts - is a great source of finding ways to create a websocket RPC environment.
A human readable JSON text is sent between the server and client sides.
Default protocol to use is WS.
In fact you can implement any protocol you want to use with the lib.
rpc-with-types is tested against:
- nodejs 20.11.0
- bun 1.0.26
interface Session {
lastMessage: string
};
const server = new Server<Session>({ sessionInit: () => { lastMessage: "" } /* other params */});
server.onEvent(..., (message: string, { _socket, session } => {
session.lastMessage = message;
}))