1.0.1 • Published 6 years ago
@jordanmcdonough/server-to-server v1.0.1
Import dependencies:
import { message, listen, server, connect, createConnection } from "@jordanmcdonough/server-to-server";
Initialise the global connection: The connect command initialises and updates the global connection if already intiialised All servers with the old connection, and future servers will default to whatever is updated in connect, unless specified in the creation
setup({
host: 'localhost',
post: 28015, //optional
db: 'example_database',
user: 'username',
password: 'password'
});
//or
setup({
connection: rethinkdbConnection
});
const anotherConnection = createConnection({
host: 'localhost',
post: 28015, //optional
db: 'example_database',
user: 'username',
password: 'password'
});
Create a server you want to communicate with e.g. server('example_server') will use the default connection OR server({
})
const server = server('example_server'); // Will use the default connection
const anotherServer = server('example_server', anotherConnection); // Will create a server on a different connection
const anotherServer = server({
name: 'example_server',
connection: anotherConnection
}); //Another way to create the server
Communicate with the server
let payload = {
userId: 1,
message: 'Hello World'
};
server.message('user-message', payload); //Send a message with a type
message(server, 'user-message', payload); // Another way using helper function
server.message(payload); //Message without an empty type = {payload} vs {type, payload}
message(server, payload); // Another way using helper function
Listen as the server
let listenFunction = (p) => {
console.log(p); // = payload
};
server.listen('user-message', listenFunction);
listen(server, 'user-message', listenFunction);
server.listen(listenFunction); //Listen to any without a type
listen(server, listenFunction); //Another way using helper function
server.listenAll(listenFunction); //Listens to all messages on the server
listenAll(server, listenFunction); //Another way using helper function
You can also replace the server parameter anywhere it is needed with either the server name for the default connection OR an object representing the server e.g.
message('example_server', 'user-message', payload);
message('example_server', payload);
listen('example_server', 'user-message', listenFunction);
listen('example_server', listenFunction);
listenAll('example_server', listenFunction);
let serverSettings = {
name: 'example_server',
connection: anotherConnection
};
message(serverSettings, 'user-message', payload);
message(serverSettings, payload);
listen(serverSettings, 'user-message', listenFunction);
listen(serverSettings, listenFunction);
listenAll(serverSettings, listenFunction);