kernel-rpc-client/src/index.ts

94 lines
2.1 KiB
TypeScript
Raw Normal View History

2022-07-20 07:35:58 +00:00
import {
callModule as callModuleKernel,
connectModule as connectModuleKernel,
} from "libkernel";
import {
callModule as callModuleModule,
connectModule as connectModuleModule,
} from "libkmodule";
import { ErrTuple } from "libskynet";
import type { RPCRequest } from "@lumeweb/dht-rpc-client";
const RPC_MODULE = "AQDaEPIo_lpdvz7AKbeafERBHR331RiyvweJ6OrFTplzyg";
let callModule: typeof callModuleModule,
connectModule: typeof connectModuleModule;
2022-07-20 21:22:10 +00:00
if (typeof window !== "undefined" && window?.document) {
2022-07-20 07:35:58 +00:00
callModule = callModuleKernel;
connectModule = connectModuleKernel;
} else {
callModule = callModuleModule;
connectModule = connectModuleModule;
}
type PromiseCB = () => Promise<ErrTuple>;
2022-07-20 07:35:58 +00:00
export class RpcNetwork {
private _actionQueue: PromiseCB[] = [];
2022-07-20 07:35:58 +00:00
get ready(): Promise<ErrTuple> {
return callModule(RPC_MODULE, "ready");
}
public addRelay(pubkey: string): void {
this._actionQueue.push(() =>
callModule(RPC_MODULE, "addRelay", { pubkey })
);
2022-07-20 07:35:58 +00:00
}
public removeRelay(pubkey: string): void {
this._actionQueue.push(() =>
callModule(RPC_MODULE, "removeRelay", { pubkey })
);
2022-07-20 07:35:58 +00:00
}
public clearRelays(): void {
this._actionQueue.push(() => callModule(RPC_MODULE, "clearRelays"));
2022-07-20 07:35:58 +00:00
}
public query(
query: string,
chain: string,
data: object | any[] = {},
force: boolean = false
): RpcQuery {
return new RpcQuery(this, {
query,
chain,
data,
force: force,
});
}
public async processQueue(): Promise<void> {
2022-07-20 22:36:47 +00:00
for (const promise of this._actionQueue.reverse()) {
try {
const p = promise();
await p;
} catch (e: any) {}
}
2022-07-20 07:35:58 +00:00
this._actionQueue = [];
}
}
export class RpcQuery {
private _promise: Promise<any>;
constructor(network: RpcNetwork, query: RPCRequest) {
this._promise = network
.processQueue()
.then(() => callModule(RPC_MODULE, "query", query));
}
get result(): Promise<any> {
return this._promise.then((result) => {
if (result[1]) {
throw new Error(result[1]);
}
return result[0];
});
}
}