Module: crossbarjs

Encapsulates crossbar publish/subscribe and register/unregister/call functionality into a facade, easier to use and reason about.

Version:
  • 1.2.0
Author:
  • Pedro Miguel P. S. Martins
Source:

Methods


<inner> call(rpcName, args)

Calls the RPC with the given name, providing the given arguments.
Resolves if it succeeds, rejects otherwise.

Parameters:
Name Type Argument Description
rpcName string

The name of the RPC we wish to call.

args Object <repeatable>

Variable number of arguments we wish to
pass.

Source:
Returns:
Type
Promise
Examples

Call an RPC with no arguments:

//Assuming we have previously connected and registered the RPC "hello"

 const hello = () => {
     console.log("Hello World");
 };

 crossbar.call("hello")
     .then(() => console.log("great success!"))
     .catch(console.log);

 

Call an RPC with multiple arguments:

//Assuming we have previously connected and registered the RPC "add"

 const add = (n1, n2) => n1 + n2;

 crossbar.call("add", 1, 2)
     .then(sum => console.log(`sum is: ${sum}`))
     .catch(console.log);

<inner> connect( [connectOpts])

Connects this instance to the given direction.
Resolves if a connection is established and opened successfully.
If it fails to open the connection, it rejects with a reason and an optional details object.

Parameters:
Name Type Argument Description
connectOpts Object <optional>

Connection object with the
options to connect.
The provided Object must have both
an url and a
realm properties to
properly connect or else it fails.
If no object is passed, the
function will use the default object.

Properties
Name Type Argument Default Description
url string <optional>
"ws://localhost:8080/ws"

The connection 'url' as described in autobahn connection options.

realm string <optional>
"realm1"

The connection 'realm' as described in autobahn connection options.

Source:
See:
Returns:
Type
Promise
Examples

Creates a connection with the default parameters:

const crossbarjs = require("crossbarjs");

 const crossbar  = crossbarjs();
 crossbar.connect()
   .then(() => console.log("Great Success!"))
   .catch((reason, details) => {
       console.log(`Failed becasue ${reason}: ${JSON.stringify(details)}`);
   });

 

Creates a connections with custom parameters:

const crossbarjs = require("crossbarjs");

 const crossbar  = crossbarjs();
 const connectParams = {url: "myURL", realm: "Lovecraft"};
 crossbar.connect(connectParams)
   .then(() => console.log("Great Success!"))
   .catch((reason, details) => {
       console.log(`Failed becasue ${reason}: ${JSON.stringify(details)}`);
   });

 

Additionally, you may also change the "options.connect":

const crossbarjs = require("crossbarjs");

 const crossbar  = crossbarjs();

 crossbar.setOpts({
   connect: { url: "myURL", realm: "Lovecraft" }
 });

 crossbar.connect()
   .then(() => console.log("Great Success!"))
   .catch((reason, details) => {
       console.log(`Failed becasue ${reason}: ${JSON.stringify(details)}`);
   });

<inner> disconnect( [reason] [, message])

Closes the crossbar connection. Resolves once the connection is closed or rejects if there was an error closing.

Parameters:
Name Type Argument Default Description
reason string <optional>
"wamp.goodbye.normal"

WAMP URI providing a closing reason e.g. 'com.myapp.close.signout' to the server side.

message string <optional>

Human-readable closing message.

Source:
Returns:
Type
Promise
Examples

Simply disconnect:

//imagine we have previously connected
 crossbar.disconnect()
   .then(() => console.log("disconnected!"))
   .catch(console.log);

 

Disconnect after connecting:

const crossbarjs = require("crossbarjs");

 const crossbar  = crossbarjs();
 crossbar.connect()
   .then(() => console.log("connected!"))
   .then(() => crossbar.disconnect("com.myapp.close.signout", "client does not like our service !!!!"))
   .then(() => console.log("disconnected!"))
   .catch(console.log);

Error while disconnecting:

const crossbarjs = require("crossbarjs");

 const crossbar  = crossbarjs();
 crossbar.disconnect()
   .catch(console.log);  //error, we never connected in the first place!

<inner> getConnection()

Returns the current autobahn.Connection object.

Source:
See:
Returns:
Type
Connection
Example

Using a connection:

//Assuming we have previously connected
 const conn = crossbar.getConnection();

<inner> getOpts()

Returns a clone of the options object.

Source:
Returns:
Type
options
Example

Get a clone of the options object:

let opts = crossbar.getOpts();
 opts = {};  //this wont alter the object being used in crossbarjs

<inner> getSession()

Returns the current autobahn.Session object.
Ideally you shouldn't need to use it with the current interface, but in case you need you can have direct access to it.

Source:
See:
Returns:
Type
Session
Example

Using a session:

//Assuming we have previously connected
 const session = crossbar.getSession();
 console.log(`Session id is: ${session.id}`);

<inner> onClose(fun)

Hook for when the connection closes. This usually happens when crossbar itself dies or closes its connections.
The passed function will receive 2 parameters, reason, a human readable reason for why the connection was closed, and a second optional parameter details, an object containing the details of why the connection was closed. This second parameter is not always passed.

Parameters:
Name Type Description
fun function

The function to be called when a connection closes.

Source:
Throws:

If fun is not a function.

Type
TypeError
Example

Creating a hook that logs when a connection was closed:

const crossbarjs = require("crossbarjs");

const crossbar  = crossbarjs();
crossbar.connect()
   .then(() => crossbar.onClose(console.log))  //if crossbar dies, this gets fired
   .catch((reason, details) => {
       console.log(`Failed becasue ${reason}: ${JSON.stringify(details)}`);
});

<inner> onError(fun)

Hook for when an error occurs. Errors may occur when crossbarjs is attempting automatic reconnection or becasue some other component failed.
The passed function will receive the error as a parameter.

Parameters:
Name Type Description
fun function

The function to be called when an Error occurs.

Source:
Throws:

If fun is not a function.

Type
TypeError
Example

Creating a hook that logs when an error occurs:

const crossbarjs = require("crossbarjs");

const crossbar  = crossbarjs();
crossbar.onRecover(error => console.log(`Got error: ${error}`));

<inner> onOpen(fun)

Hook for when the connection opens. This usually happens when the application first connects to crossbar and when the connection is lost and later on recovered.
The passed function will receive no parameters.

Parameters:
Name Type Description
fun function

The function to be called when a connection opens.

Source:
Throws:

If fun is not a function.

Type
TypeError
Example

Creating a hook that logs when a connection opens:

const crossbarjs = require("crossbarjs");

const crossbar  = crossbarjs();
crossbar.onOpen(() => console.log("I'm alive!"));
crossbar.connect()
   .catch((reason, details) => {
       console.log(`Failed becasue ${reason}: ${JSON.stringify(details)}`);
});

<inner> onRecover(fun)

Hook for when the connection recovers. A connection recovers when it has closed unexpectadly and then reconnects activating the recover proceaduer, that re-subscribes and re-registers any calls previously done automatically.
The passed function will receive no parameters.

Parameters:
Name Type Description
fun function

The function to be called when a connection recovers.

Source:
Throws:

If fun is not a function.

Type
TypeError
Example

Creating a hook that logs when a connection recovers:

const crossbarjs = require("crossbarjs");

const crossbar  = crossbarjs();
crossbar.onRecover(() => console.log("I'm back baby!"));
crossbar.connect()
   .catch((reason, details) => {
       console.log(`Failed becasue ${reason}: ${JSON.stringify(details)}`);
});
//kill crossbar
//start crossbar
//message should appear

<inner> publish(topic, params)

Publishes the given topic with the given list of variable parameters.
Resolves if it succeeds, rejects otherwise.

Parameters:
Name Type Argument Description
topic string

The topic of the message.

params Object <repeatable>

The parameters that the subscribed
functions will receive.

Source:
Returns:
Type
Promise
Example

Publish a topic:

//Assuming we are already connected
 crossbar.publish("add", 1, 2)
     .then(() => console.log("Published!"))
     .catch(console.log);

<inner> register(args)

Registers the given RPCs, biinding each RPC to a name.
It can either register a single RPC, or an array of RPC objects.
Resolves if all RPCs were registered successfully or rejects if one of them fails.

Parameters:
Name Type Description
args string | Array.<RPC>

It can either receive two arguments,
a string and a function, to register
one RPC, or it can receive an array of
RPC objects, to register them all.

Source:
Returns:
Type
Promise
Examples

Registering a single RPC:

//Assuming we have previously connected
 const myHello = () => {
     console.log("Hello World");
 }

 crossbar.register("hello", myHello)
     .then(() => console.log("great success!"))
     .catch(console.log);

 

Registering multiple RPCs:

//Assuming we have previously connected
 const myHello = () => {
     console.log("Hello World");
 }

 const myGoodbye = () => {
     console.log("Goodbye World!");
 };

 const RPCs = [
     { name: "hello" , func: myHello   },
     { name: "bye"   , func: myGoodbye }
 ];

 crossbar.register(RPCs)
     .then(() => console.log("great success!"))
     .catch(console.log);

<inner> setOpts(newOpts)

Concatenates the given options object with the current one.
This is the only way to change the options object.

Parameters:
Name Type Description
newOpts Object

The options we want to add.

Source:
See:
Example

Add publish parameters to the options object:

crossbar.setOpts({
     publish: { some options }
 });
 console.log(JSON.stringify(crossbar.getOpts()));
 //will print
 //{
 //  connect: {
 //    "url": "ws://localhost:8080/ws",
 //    "realm": "realm1"
 //  },
 //  publish: { some options },
 //  subscribe: {},
 //  call: {},
 //  register: {}
 //}

<inner> setOptsDefault()

Resets the options object to its default state.

Source:
See:

<inner> subscribe(topic, callback)

Subscribes to the given topic, executing the function every time crossbar receives a message.
Resolves if the subscription was successful, rejects otherwise.

Parameters:
Name Type Description
topic string

The topic to wich we want to subscribe.

callback function

The function to execute every time we
receive a message.

Source:
Returns:
Type
Promise
Example

Subscribe to the topic "add". See publish:

//Assuming we are already connected
 const myAdd = (n1, n2) => n1 + n2;

 crossbar.subscribe("add", myAdd);
     .then(() => console.log("Subscribed!"))
     .catch(console.log);

<inner> unregister(args)

Unregisters the RPC with the given name, or all the RPCs with the names provided in the array.
Returns a promise once all RPCs have be unregistered successfully or rejects if one of them fails.

Parameters:
Name Type Argument Description
args string <repeatable>

The names of the RPCs to unregister

Source:
Returns:
Type
Promise
Examples

Unregister a single RPC:

//Assuming we have previously connected and registered "hello"
 crossbar.unregister("hello")
     .then(() => console.log("great success!"))
     .catch(console.log);

 

Unregister multiple RPCs:

//Assuming we have previously connected and registered the RPCs with the given names
 crossbar.unregister("hello", "bye")
     .then(() => console.log("great success!"))
     .catch(console.log);

<inner> unsubscribe(topic)

Unsubscribes from the given topic. Resolves if successful,
rejects otherwise.

Parameters:
Name Type Description
topic string

The topic to which we want to unsubscribe.

Source:
Returns:
Type
Promise
Example

Unsubscribe to the topic "add". See subscribe:

//Assuming we are already connected
 crossbar.unsubscribe("add");
     .then(() => console.log("Unsubscribed!"))
     .catch(console.log);