kernel-rpc-client/dist/index.js

62 lines
1.8 KiB
JavaScript
Raw Normal View History

2022-07-20 07:36:21 +00:00
import { callModule as callModuleKernel, connectModule as connectModuleKernel, } from "libkernel";
import { callModule as callModuleModule, connectModule as connectModuleModule, } from "libkmodule";
const RPC_MODULE = "AQDaEPIo_lpdvz7AKbeafERBHR331RiyvweJ6OrFTplzyg";
let callModule, connectModule;
2022-07-20 21:22:25 +00:00
if (typeof window !== "undefined" && window?.document) {
2022-07-20 07:36:21 +00:00
callModule = callModuleKernel;
connectModule = connectModuleKernel;
}
else {
callModule = callModuleModule;
connectModule = connectModuleModule;
}
export class RpcNetwork {
_actionQueue = [];
get ready() {
return callModule(RPC_MODULE, "ready");
}
addRelay(pubkey) {
2022-07-20 22:25:47 +00:00
this._actionQueue.push(() => callModule(RPC_MODULE, "addRelay", { pubkey }));
2022-07-20 07:36:21 +00:00
}
removeRelay(pubkey) {
2022-07-20 22:25:47 +00:00
this._actionQueue.push(() => callModule(RPC_MODULE, "removeRelay", { pubkey }));
2022-07-20 07:36:21 +00:00
}
clearRelays() {
2022-07-20 22:25:47 +00:00
this._actionQueue.push(() => callModule(RPC_MODULE, "clearRelays"));
2022-07-20 07:36:21 +00:00
}
query(query, chain, data = {}, force = false) {
return new RpcQuery(this, {
query,
chain,
data,
force: force,
});
}
async processQueue() {
for (const promise of this._actionQueue) {
try {
2022-07-20 22:32:09 +00:00
const p = promise();
await p;
}
2022-07-20 21:22:25 +00:00
catch (e) { }
}
2022-07-20 07:36:21 +00:00
this._actionQueue = [];
}
}
export class RpcQuery {
_promise;
constructor(network, query) {
this._promise = network
.processQueue()
.then(() => callModule(RPC_MODULE, "query", query));
}
get result() {
return this._promise.then((result) => {
if (result[1]) {
throw new Error(result[1]);
}
return result[0];
});
}
}