JSON-RPC 2.0 library (server and client) with HTTP and WebSockets support for deno and the browser.
Takes Methods
, ServerRequest
and Options
. Look
here
for more information about Options
.
import { listenAndServe } 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(" "),
};
listenAndServe("0.0.0.0:8000", (req) => respond(rpcMethods, req));
console.log("listening on 0.0.0.0:8000");
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,
);
//..
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"));
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
Using the option { isNotification: true }
will retun Promise<undefined>
.
const notification = await remote.call("sayHello", ["World"], {
isNotification: true,
});
// undefined
Adding the option {jwt: string}
will set the Authorization
header to
`Bearer ${jwt}`
.
const user = await remote.call("login", undefined, { jwt });
// Bob
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" }
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>
.
const notification = await remote.call("animalsMakeNoise", ["wuufff"], {
isNotification: true,
});
// undefined
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
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
Please checkout the examples and tests folders for more detailed examples.
Every kind of contribution to this project is highly appreciated.
Please run deno fmt
on the changed files before making a pull request.