Split commandHandler in smaller pure functions

This commit is contained in:
Franck Royer 2021-04-27 10:48:08 +10:00
parent a27080fc34
commit b943a88aff
No known key found for this signature in database
GPG Key ID: A82ED75A8DFC50A4
2 changed files with 122 additions and 83 deletions

View File

@ -5,6 +5,7 @@ import './App.css';
import { ChatMessage } from 'waku-chat/chat_message';
import { WakuMessage } from 'waku/waku_message';
import { RelayDefaultTopic } from 'waku/waku_relay';
import handleCommand from './command';
import Room from './Room';
import Waku from 'waku/waku';
import { WakuContext } from './WakuContext';
@ -71,95 +72,24 @@ export default function App() {
}
});
const commandHandler = (input: string) => {
let commandResponses: string[] = [];
const args = input.split(' ');
const cmd = args.shift()!;
if (!stateWaku) {
commandResponses.push('Waku is not yet initialized');
} else {
switch (cmd) {
case '/help':
commandResponses.push('/nick <nickname>: set a new nickname');
commandResponses.push('/info: some information about the node');
commandResponses.push(
'/connect <Multiaddr>: connect to the given peer'
);
commandResponses.push('/help: Display this help');
break;
case '/nick':
const arg = args.shift();
if (!arg) {
commandResponses.push('No nick provided');
} else {
setNick(arg);
commandResponses.push(`New nick: ${arg}`);
}
break;
case '/info':
if (!stateWaku) {
commandResponses.push(`Waku node is starting`);
} else {
commandResponses.push(
`PeerId: ${stateWaku.libp2p.peerId.toB58String()}`
);
}
break;
case '/connect':
const peer = args.shift();
if (!peer) {
commandResponses.push('No peer provided');
} else {
try {
const peerMultiaddr = multiaddr(peer);
const peerId = peerMultiaddr.getPeerId();
if (!peerId) {
commandResponses.push('Peer Id needed to dial');
} else {
stateWaku.libp2p.peerStore.addressBook.add(
PeerId.createFromB58String(peerId),
[peerMultiaddr]
);
}
} catch (e) {
commandResponses.push('Invalid multiaddr: ' + e);
}
}
break;
case '/peers':
stateWaku.libp2p.peerStore.peers.forEach((peer, peerId) => {
commandResponses.push(peerId + ':');
let addresses = ' addresses: [';
peer.addresses.forEach(({ multiaddr }) => {
addresses += ' ' + multiaddr.toString() + ',';
});
addresses = addresses.replace(/,$/, '');
addresses += ']';
commandResponses.push(addresses);
let protocols = ' protocols: [';
protocols += peer.protocols;
protocols += ']';
commandResponses.push(protocols);
});
break;
default:
commandResponses.push('Unknown Command');
}
}
const messages = stateMessages.slice();
commandResponses.forEach((res) => {
messages.push(new ChatMessage(new Date(), cmd, res));
});
setMessages(messages);
};
return (
<div className="chat-app">
<WakuContext.Provider value={{ waku: stateWaku }}>
<Room
nick={nick}
lines={stateMessages}
commandHandler={commandHandler}
commandHandler={(input: string) => {
const { command, response } = handleCommand(
input,
stateWaku,
setNick
);
const messages = stateMessages.slice();
response.forEach((msg) => {
messages.push(new ChatMessage(new Date(), command, msg));
});
setMessages(messages);
}}
/>
</WakuContext.Provider>
</div>

109
web-chat/src/command.ts Normal file
View File

@ -0,0 +1,109 @@
import { multiaddr } from 'multiaddr';
import PeerId from 'peer-id';
import Waku from '../../build/main/lib/waku';
function help(): string[] {
return [
'/nick <nickname>: set a new nickname',
'/info: some information about the node',
'/connect <Multiaddr>: connect to the given peer',
'/help: Display this help',
];
}
function nick(
nick: string | undefined,
setNick: (nick: string) => void
): string[] {
if (!nick) {
return ['No nick provided'];
}
setNick(nick);
return [`New nick: ${nick}`];
}
function info(waku: Waku | undefined): string[] {
if (!waku) {
return ['Waku node is starting'];
}
return [`PeerId: ${waku.libp2p.peerId.toB58String()}`];
}
function connect(peer: string | undefined, waku: Waku | undefined): string[] {
if (!waku) {
return ['Waku node is starting'];
}
if (!peer) {
return ['No peer provided'];
}
try {
const peerMultiaddr = multiaddr(peer);
const peerId = peerMultiaddr.getPeerId();
if (!peerId) {
return ['Peer Id needed to dial'];
}
waku.libp2p.peerStore.addressBook.add(PeerId.createFromB58String(peerId), [
peerMultiaddr,
]);
return [
`${peerId}: ${peerMultiaddr.toString()} added to address book, autodial in progress`,
];
} catch (e) {
return ['Invalid multiaddr: ' + e];
}
}
function peers(waku: Waku | undefined): string[] {
if (!waku) {
return ['Waku node is starting'];
}
let response: string[] = [];
waku.libp2p.peerStore.peers.forEach((peer, peerId) => {
response.push(peerId + ':');
let addresses = ' addresses: [';
peer.addresses.forEach(({ multiaddr }) => {
addresses += ' ' + multiaddr.toString() + ',';
});
addresses = addresses.replace(/,$/, '');
addresses += ']';
response.push(addresses);
let protocols = ' protocols: [';
protocols += peer.protocols;
protocols += ']';
response.push(protocols);
});
if (response.length === 0) {
response.push('Not connected to any peer.');
}
return response;
}
export default function handleCommand(
input: string,
waku: Waku | undefined,
setNick: (nick: string) => void
): { command: string; response: string[] } {
let response: string[] = [];
const args = input.split(' ');
const command = args.shift()!;
switch (command) {
case '/help':
help().map((str) => response.push(str));
break;
case '/nick':
nick(args.shift(), setNick).map((str) => response.push(str));
break;
case '/info':
info(waku).map((str) => response.push(str));
break;
case '/connect':
connect(args.shift(), waku).map((str) => response.push(str));
break;
case '/peers':
peers(waku).map((str) => response.push(str));
break;
default:
response.push(`Unknown Command '${command}'`);
}
return { command, response };
}