From 9071ed0592060619c2ee295ceeb1656e95b341e2 Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Wed, 3 Aug 2022 12:04:53 -0400 Subject: [PATCH] *add support for creating a DHT connection or using the default --- package.json | 1 + src/index.ts | 46 ++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index 59560ab..2cff392 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,7 @@ "main": "dist/index.js", "dependencies": { "buffer": "^6.0.3", + "events": "^3.3.0", "libkernel": "^0.1.43", "libkmodule": "^0.2.44", "libskynet": "^0.0.62" diff --git a/src/index.ts b/src/index.ts index 7239db5..932ad60 100644 --- a/src/index.ts +++ b/src/index.ts @@ -23,6 +23,13 @@ async function loadLibs() { } export class DHT { + private useDefaultDht: boolean; + private id: number; + + constructor(useDefaultDht = true) { + this.useDefaultDht = useDefaultDht; + } + public async connect(pubkey: string): Promise { await loadLibs(); const [resp, err] = await callModule(DHT_MODULE, "connect", {pubkey}); @@ -34,12 +41,14 @@ export class DHT { async ready(): Promise { await loadLibs(); - return callModule(DHT_MODULE, "ready"); + const dht = !this.useDefaultDht ? this.id : undefined; + return callModule(DHT_MODULE, "ready", {dht}); } public async addRelay(pubkey: string): Promise { await loadLibs(); - const [, err] = await callModule(DHT_MODULE, "addRelay", {pubkey}); + const dht = !this.useDefaultDht ? this.id : undefined; + const [, err] = await callModule(DHT_MODULE, "addRelay", {pubkey, dht}); if (err) { throw new Error(err); } @@ -47,7 +56,8 @@ export class DHT { public async removeRelay(pubkey: string): Promise { await loadLibs(); - const [, err] = await callModule(DHT_MODULE, "removeRelay", {pubkey}); + const dht = !this.useDefaultDht ? this.id : undefined; + const [, err] = await callModule(DHT_MODULE, "removeRelay", {pubkey, dht}); if (err) { throw new Error(err); } @@ -55,7 +65,35 @@ export class DHT { public async clearRelays(): Promise { await loadLibs(); - await callModule(DHT_MODULE, "clearRelays"); + const dht = !this.useDefaultDht ? this.id : undefined; + await callModule(DHT_MODULE, "clearRelays", {dht}); + } + + private async create() { + await loadLibs(); + if (this.useDefaultDht) { + return Promise.resolve(); + } + const [dht, err] = await callModule(DHT_MODULE, "openDht"); + if (err) { + throw new Error(err); + } + + this.id = dht; + } + + public async close(): Promise { + await loadLibs(); + + if (this.useDefaultDht) { + return false; + } + const [, err] = await callModule(DHT_MODULE, "closeDht", {dht: this.id}); + if (err) { + throw new Error(err); + } + + return true; } }