1.0.1 • Published 10 months ago

@cclab/cc-rpc v1.0.1

Weekly downloads
-
License
MIT
Repository
-
Last release
10 months ago

cc-rpc

Introduction

A simple RPC endpoint implementation based on JSON-RPC 2.0

Installation

npm install @cclab/cc-rpc

Usage

TypeScript

import { RpcEndpoint } from "@cclab/cc-rpc";

interface IEndpoint1 {
    plus: (params: { a: number, b: number }) => number,
    equal: (params: { c: number, d: number }) => boolean
}

interface IEndpoint2 {
    minus: (params: { a: number, b: number }) => number
}

const endpoint1 = new RpcEndpoint<IEndpoint1, IEndpoint2>();
const endpoint2 = new RpcEndpoint<IEndpoint2, IEndpoint1>();

// Enable or disable logging
endpoint1.enableLogging = true; // Enable logging
endpoint2.enableLogging = false; // Disable logging

// Register call handlers
endpoint1.onCall("plus", ({ a, b }) => a + b);
endpoint1.onCall("equal", ({ c, d }) => c === d);

// Register notify handlers
endpoint1.onNotify("hello", ({ msg }) => {
    console.log(`Received hello message: ${msg}`);
});

// Example of making a call
async function performRpcCalls() {
    try {
        const result = await endpoint2.call("plus", { a: 5, b: 3 });
        console.log(`Result of plus: ${result}`);
    } catch (error) {
        console.error(`Error during RPC call: ${error}`);
    }
}

// Example of sending a notification
endpoint2.notify("hello", { msg: "Hello, world!" });

performRpcCalls();

JavaScript

const { RpcEndpoint } = require("@cclab/cc-rpc");

const endpoint1 = new RpcEndpoint();
const endpoint2 = new RpcEndpoint();

// Enable or disable logging
endpoint1.enableLogging = true; // Enable logging
endpoint2.enableLogging = false; // Disable logging

// Register call handlers
endpoint1.onCall("plus", ({ a, b }) => a + b);
endpoint1.onCall("equal", ({ c, d }) => c === d);

// Register notify handlers
endpoint1.onNotify("hello", ({ msg }) => {
    console.log(`Received hello message: ${msg}`);
});

// Example of making a call
async function performRpcCalls() {
    try {
        const result = await endpoint2.call("plus", { a: 5, b: 3 });
        console.log(`Result of plus: ${result}`);
    } catch (error) {
        console.error(`Error during RPC call: ${error}`);
    }
}

// Example of sending a notification
endpoint2.notify("hello", { msg: "Hello, world!" });

performRpcCalls();