Skip to content

Commit

Permalink
refactor: separate message processing
Browse files Browse the repository at this point in the history
  • Loading branch information
DIY0R committed Oct 16, 2024
1 parent 453fdd6 commit f10050d
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 17 deletions.
4 changes: 3 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
const Messaging = require('./lib/messaging');
module.exports = { ClapPeer: Messaging };
const constants = require('./lib/constants');

module.exports = { ClapPeer: Messaging, ...constants };
1 change: 1 addition & 0 deletions lib/constants.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const HANDSHAKE = 'HANDSHAKE';
const DM = 'MESSAGE';

module.exports = { HANDSHAKE, DM };
34 changes: 18 additions & 16 deletions lib/messaging.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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) {
Expand All @@ -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);
}
}

Expand Down

0 comments on commit f10050d

Please sign in to comment.