*Add removeRelay and clearRelays API methods

This commit is contained in:
Derrick Hammer 2022-07-20 18:03:10 -04:00
parent 2c41826632
commit 179bef1f9f
1 changed files with 80 additions and 69 deletions

View File

@ -6,9 +6,9 @@ import {
callModule as callModuleModule,
connectModule as connectModuleModule,
} from "libkmodule";
import { EventEmitter } from "events";
import { DataFn, ErrTuple } from "libskynet";
import { Buffer } from "buffer";
import {EventEmitter} from "events";
import {DataFn, ErrTuple} from "libskynet";
import {Buffer} from "buffer";
const DHT_MODULE = "AQD1IgE4lTZkq1fqdoYGojKRNrSk0YQ_wrHbRtIiHDrnow";
@ -25,7 +25,7 @@ if (typeof window !== "undefined" && window?.document) {
export class DHT {
public async connect(pubkey: string): Promise<Socket> {
const [resp, err] = await callModule(DHT_MODULE, "connect", { pubkey });
const [resp, err] = await callModule(DHT_MODULE, "connect", {pubkey});
if (err) {
throw new Error(err);
}
@ -37,11 +37,22 @@ export class DHT {
}
public async addRelay(pubkey: string): Promise<void> {
const [, err] = await callModule(DHT_MODULE, "addRelay", { pubkey });
const [, err] = await callModule(DHT_MODULE, "addRelay", {pubkey});
if (err) {
throw new Error(err);
}
}
public async removeRelay(pubkey: string): Promise<void> {
const [, err] = await callModule(DHT_MODULE, "removeRelay", {pubkey});
if (err) {
throw new Error(err);
}
}
public async clearRelays(): Promise<void> {
await callModule(DHT_MODULE, "clearRelays");
}
}
export class Socket extends EventEmitter {
@ -57,7 +68,7 @@ export class Socket extends EventEmitter {
const [update, promise] = connectModule(
DHT_MODULE,
"listenSocketEvent",
{ id: this.id, event: eventName },
{id: this.id, event: eventName},
(data: any) => {
this.emit(eventName, data);
}
@ -75,17 +86,17 @@ export class Socket extends EventEmitter {
const updates = [...this.eventUpdates[type]];
this.eventUpdates[type] = [];
for (const func of updates) {
func({ action: "off" });
func({action: "off"});
}
return super.off(type, listener);
}
write(message: string | Buffer): void {
callModule(DHT_MODULE, "write", { id: this.id, message });
callModule(DHT_MODULE, "write", {id: this.id, message});
}
end(): void {
callModule(DHT_MODULE, "close", { id: this.id });
callModule(DHT_MODULE, "close", {id: this.id});
}
private ensureEvent(event: string): void {