From f10050dd3470ae98deb6082974865b5b30b138a9 Mon Sep 17 00:00:00 2001 From: diy0r Date: Wed, 16 Oct 2024 14:24:15 +0500 Subject: [PATCH] refactor: separate message processing --- index.js | 4 +++- lib/constants.js | 1 + lib/messaging.js | 34 ++++++++++++++++++---------------- 3 files changed, 22 insertions(+), 17 deletions(-) diff --git a/index.js b/index.js index c08a374..c7171ab 100644 --- a/index.js +++ b/index.js @@ -1,2 +1,4 @@ const Messaging = require('./lib/messaging'); -module.exports = { ClapPeer: Messaging }; +const constants = require('./lib/constants'); + +module.exports = { ClapPeer: Messaging, ...constants }; diff --git a/lib/constants.js b/lib/constants.js index 383c637..7f30955 100644 --- a/lib/constants.js +++ b/lib/constants.js @@ -1,3 +1,4 @@ const HANDSHAKE = 'HANDSHAKE'; const DM = 'MESSAGE'; + module.exports = { HANDSHAKE, DM }; diff --git a/lib/messaging.js b/lib/messaging.js index b2b16be..021e7b2 100644 --- a/lib/messaging.js +++ b/lib/messaging.js @@ -17,15 +17,9 @@ class Messaging extends Connection { } _onMessage(connectionId, messageObject) { - const { type, data, to } = messageObject; - this[type](data); - if (type === HANDSHAKE) { - this.#addNeighbor(connectionId, data); - } - if (type === DM) { - if (to !== this.NODE_ID) return this.send(to, data); - this.emit(DM, data); - } + const { type } = messageObject; + const handler = this[type]?.bind(this); + if (handler) handler(connectionId, messageObject); } _deleteConnection(connectionId) { @@ -35,12 +29,10 @@ class Messaging extends Connection { send(nodeId, message) { const connectionId = this.neighbors.get(nodeId); - if (connectionId) - return this._send( - connectionId, - createMessage({ type: DM, data: message, to: nodeId }), - ); - this.neighbors.forEach(connectionId => this._send(connectionId, message)); + const targets = connectionId ? [connectionId] : this.neighbors; + targets.forEach(target => + this._send(target, createMessage(DM, nodeId, message)), + ); } #findNodeId(connectionId) { @@ -51,7 +43,17 @@ class Messaging extends Connection { #addNeighbor(connectionId, neighbor) { this.neighbors.set(neighbor, connectionId); - console.log(this.neighbors.get(neighbor)); + } + + [HANDSHAKE](connectionId, messageObject) { + const { data } = messageObject; + this.#addNeighbor(connectionId, data); + } + + [DM](_, messageObject) { + const { data, to } = messageObject; + if (to !== this.NODE_ID) return this.send(to, data); + this.emit(DM, data); } }