rpc-client/dist/query/simple.js

63 lines
1.8 KiB
JavaScript
Raw Normal View History

2022-12-04 07:42:04 +00:00
import b4a from "b4a";
2022-12-04 11:37:24 +00:00
import { hashQuery, isPromise, validateTimestampedResponse, } from "../util.js";
2022-12-04 07:42:04 +00:00
import RPC from "@lumeweb/rpc";
import { ERR_INVALID_SIGNATURE } from "../error.js";
2022-08-28 06:33:49 +00:00
import RpcQueryBase from "./base.js";
export default class SimpleRpcQuery extends RpcQueryBase {
_relay;
constructor(network, relay, query, options) {
super(network, query, options);
this._relay = relay;
}
2022-12-04 07:42:04 +00:00
async _run() {
await this.queryRelay();
await this.checkResponses();
}
async queryRelay() {
let socket;
try {
socket = this._network.dht.connect(b4a.from(this._relay, "hex"));
if (isPromise(socket)) {
socket = await socket;
}
}
catch (e) {
2022-08-28 06:33:49 +00:00
return;
}
2022-12-04 07:42:04 +00:00
await socket.opened;
const rpc = new RPC(socket);
2022-12-04 11:37:24 +00:00
if (this._query.bypassCache) {
delete this._query.bypassCache;
await this.queryRpc(rpc, {
module: "rpc",
method: "clear_cached_item",
data: hashQuery(this._query),
});
}
if ("bypassCache" in this._query) {
delete this._query.bypassCache;
}
2022-12-04 07:42:04 +00:00
try {
await this.queryRpc(rpc, this._query);
}
catch (e) {
// @ts-ignore
rpc.end();
throw e;
2022-08-28 06:33:49 +00:00
}
2022-12-04 07:42:04 +00:00
// @ts-ignore
rpc.end();
2022-08-28 06:33:49 +00:00
}
2022-12-04 07:42:04 +00:00
async checkResponses() {
let response = this._response;
if (this._error) {
response = { error: this._error };
}
if (!response.error &&
!validateTimestampedResponse(b4a.from(this._relay, "hex"), response)) {
response = { error: ERR_INVALID_SIGNATURE };
}
this.resolve(response);
2022-08-28 06:33:49 +00:00
}
}