Giter Site home page Giter Site logo

timonson / gentle_rpc Goto Github PK

View Code? Open in Web Editor NEW
45.0 2.0 9.0 233 KB

JSON-RPC 2.0 library with HTTP and WebSockets support for deno and the browser

License: MIT License

TypeScript 100.00%
json-rpc2 deno typescript fetch rpc browser esmodules websocket websockets javascript

gentle_rpc's Introduction

gentle_rpc

JSON-RPC 2.0 library (server and client) with HTTP and WebSockets support for deno and the browser.

Important Notice

The gentle_rpc library is no longer maintained. Please switch to our new and improved RPC library, schicksal, available at schicksal on GitHub.

Server

respond

Takes Methods, ServerRequest and Options. Look here for more information about Options.

import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { respond } from "https://deno.land/x/gentle_rpc/mod.ts";

const rpcMethods = {
  sayHello: ([w]: [string]) => `Hello ${w}`,
  callNamedParameters: ({ a, b, c }: { a: number; b: number; c: string }) =>
    `${c} ${a * b}`,
  animalsMakeNoise: (noise: string[]) =>
    noise.map((el) => el.toUpperCase()).join(" "),
};

serve((req) => respond(rpcMethods, req), { addr: ":8000" });

console.log("Listening on http://localhost:8000");

CustomError

Throw a CustomError to send a server-defined error response.

import { CustomError, respond } from "https://deno.land/x/gentle_rpc/mod.ts";

//..
await respond(
  {
    throwError: () => {
      throw new CustomError(
        -32040, // the JSON-RPC error code. Note, must be -32040 to -32099
        "An error occurred", // the error message, a short sentence
        { details: "..." }, // optional additional details, can be any `JsonValue`
      );
    },
  },
  req,
);
//..

Client

createRemote

Takes a Resource for HTTP or a WebSocket for WebSockets and returns Remote.

import { createRemote } from "https://deno.land/x/gentle_rpc/mod.ts";
// Or import directly into the browser with:
import { createRemote } from "https://cdn.jsdelivr.net/gh/timonson/[email protected]/client/dist/remote.js";

// HTTP:
const remote = createRemote("http://0.0.0.0:8000");

// WebSocket:
const remote = await createRemote(new WebSocket("ws://0.0.0.0:8000"));

HTTP

call

Takes a string and an Array<JsonValue> or Record<string, JsonValue> object and returns Promise<JsonValue>.

const greeting = await remote.call("sayHello", ["World"]);
// Hello World

const namedParams = await remote.call("callNamedParameters", {
  a: 5,
  b: 10,
  c: "result:",
});
// result: 50
notification

Using the option { isNotification: true } will retun Promise<undefined>.

const notification = await remote.call("sayHello", ["World"], {
  isNotification: true,
});
// undefined
jwt

Adding the option {jwt: string} will set the Authorization header to `Bearer ${jwt}`.

const user = await remote.call("login", undefined, { jwt });
// Bob

batch

const noise1 = await remote.batch([
  {
    animalsMakeNoise: [
      ["miaaow"],
      ["wuuuufu", "wuuuufu"],
      ["iaaaiaia", "iaaaiaia", "iaaaiaia"],
      ["fiiiiire"],
    ],
    sayHello: [["World"], undefined, ["World"]],
  },
]);
// [ "MIAAOW", "WUUUUFU WUUUUFU", "IAAAIAIA IAAAIAIA IAAAIAIA", "FIIIIIRE", "Hello World", "Hello ", "Hello World" ]

The following example uses the object keys cat, dog, donkey, dragon as RPC request object ids under the hood. The returned RPC result values will be assigned to these keys.

let noise2 = await remote.batch({
  cat: ["sayHello", ["miaaow"]],
  dog: ["animalsMakeNoise", ["wuuuufu"]],
  donkey: ["sayHello"],
  dragon: ["animalsMakeNoise", ["fiiiiire", "fiiiiire"]],
});
// { cat: "Hello miaaow", dog: "WUUUUFU", donkey: "Hello ", dragon: "FIIIIIRE FIIIIIRE" }

WebSockets

call

Takes a string and an Array<JsonValue> or Record<string, JsonValue> object and returns Promise<JsonValue>.

const noise = await remote.call("callNamedParameters", {
  a: 10,
  b: 20,
  c: "The result is:",
});
// The result is: 200

remote.socket.close();

Notifications return Promise<undefined>.

notification
const notification = await remote.call("animalsMakeNoise", ["wuufff"], {
  isNotification: true,
});
// undefined
messaging between multiple clients

By using the subscribe method you can send messages between multiple clients. It returns an object with a generator property { generator: AsyncGenerator<JsonValue>} and the methods emit and unsubscribe.

Other clients can listen to and emit messages by subscribing to the same method.

const firstClient = await createRemote(new WebSocket("ws://0.0.0.0:8000"));
const secondClient = await createRemote(new WebSocket("ws://0.0.0.0:8000"));

async function run(iter: AsyncGenerator<unknown>) {
  try {
    for await (let x of iter) {
      console.log(x);
    }
  } catch (err) {
    console.log(err.message, err.code, err.data);
  }
}

const greetingFirst = firstClient.subscribe("sayHello");
const greetingSecond = secondClient.subscribe("sayHello");

run(greetingFirst.generator);
run(greetingSecond.generator);
greetingFirst.emit(["first"]);
greetingSecond.emit(["second"]);
// Hello first
// Hello first
// Hello second
// Hello second

Proxy API

Optionally, you can import syntactical sugar and use a more friendly API supported by Proxy objects.

import {
  createRemote,
  HttpProxy,
  httpProxyHandler,
} from "https://deno.land/x/gentle_rpc/mod.ts";

const remote = new Proxy<HttpProxy>(
  createRemote("http://0.0.0.0:8000"),
  httpProxyHandler,
);

let greeting = await remote.sayHello(["World"]);
// Hello World

const namedParams = await remote.callNamedParameters({
  a: 5,
  b: 10,
  c: "result:",
});
// result: 50

Examples and Tests

Please checkout the examples and tests folders for more detailed examples.

Contribution

Every kind of contribution to this project is highly appreciated.
Please run deno fmt on the changed files before making a pull request.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.