autobus
v1.0.0
Published
Bus for Node & Browserify
Downloads
1,466
Readme
autobus
Bus for Node & Browserify
Purpose
Send messages between channels and add listener functions to receive messages.
Installation
npm install autobus
Usage Example
import AutoBus from 'autobus';
interface ChatMessage {
text: string;
user: string;
date: Date;
}
const displayMessage = (message: ChatMessage) => {
const { text, user, date } = message;
const formattedDate = date.toTimeString().split(' ')[0];
console.log(`[${formattedDate}] ${user}: ${text}`);
};
class ChatSession {
constructor(autoBus: AutoBus, user: string) {
this.autoBus = autoBus;
this.user = user;
this.init();
}
init() {
this.autoBus.join('chat.channel', this.onMessageReceived.bind(this));
}
onMessageReceived(message: ChatMessage) {
if (message.user === this.user) {
return;
}
displayMessage(message);
}
publishMessage(message: string) {
const chatMessage: ChatMessage = {
text: message,
user: this.user,
date: new Date()
};
this.autoBus.publish('chat.channel', chatMessage);
}
}
const autoBus = new AutoBus();
const session1 = new ChatSession(autoBus, 'User1');
const session2 = new ChatSession(autoBus, 'User2');
session1.publishMessage("Hello I'm User1");
session2.publishMessage("Hello I'm User2");
Example output
[12:30:28] User1: Hello I'm User1
[12:30:28] User2: Hello I'm User2
Methods
join(channel, listener)
Adds listener to channel (creates channel if it doesn't exist)
const autoBus = new AutoBus();
const consoleLogData = (data: any) => {
console.log(data);
};
autoBus.join('example.channel', consoleLogData);
Wildcard Matching
Join channel with wildcard name matching
autoBus.join('*.channel', consoleLogData);
send(channel, message)
Sends message to one listener on the channel, if there is more than one listener on the channel the method throws an error.
autoBus.send('example.channel', 'example message');
publish(channel, message)
Sends message to all listeners on the channel.
autoBus.publish('example.channel', 'example message');
leave(channel, listener)
Remove listener from channel
autoBus.leave('example.channel', consoleLogData);