Get started

Here is a quick walkthrough on how to put the library to use in your project.

Install

Sarus can be installed using npm:

Install Sarus
Copy
npm i @anephenix/sarus

Usage and attaching event listeners

Once you have installed the library, you can include it in your project's code like this:

Initial Setup
Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// import the module 
import Sarus from '@anephenix/sarus';

/*
  If you know what event listener functions you want
  to bind to the WebSocket connection, you can pass
  them directly to Sarus at the time of creating the
  connection: 
*/

// Log a message that the connection is open
const noteOpened = () => console.log('Connection opened');

// Assuming that the WebSocket server is sending JSON data,
// you can use this to parse the data payload;
const parseMessage = event => {
  const message = JSON.parse(event.data);
  // Then do what you like with the message
};

// Log a message that the connection has closed
const noteClosed = () => console.log('Connection closed');

// If an error occurs, throw the error
const throwError = error => throw error;

// Create an instance of Sarus with the event listeners
const sarus = new Sarus({
  url: 'wss://echo.websocket.org',
  eventListeners: {
    open: [noteOpened],
    message: [parseMessage],
    close: [notedClosed],
    error: [throwError]
  }
});

You can also attach event listeners to the instance of Sarus after creating it, giving you lots of flexibility in how you interact with events on the WebSocket:

Attach event listeners
Copy
1
2
3
4
5
6
7
// Logs messages to the console for debugging
const logMessage = (event) => {
  console.log(event.data);
};

// Attach the event listener
sarus.on('message', logMessage);

You can also unattach event listeners from the Sarus instance:

detach event listeners
Copy
1
2
3
4
5
6
7
8
9
10
11
/*
  Remove a function from the Sarus 
  event listener by function variable
*/
sarus.off('message', logMessage);

/*
  You can also remove the event Listener 
  by the name of the function
*/
sarus.off('message', 'parseMessage');

Sending messages

Sending messages in Sarus is identical to how you would send messages with a WebSocket:

Send messages
Copy
1
sarus.send('Hello world');

Closing the connection

If you want to close the WebSocket connection (for example when the user logs off from an app), then you can do that by calling this:

Close the connection
Copy
1
sarus.disconnect();

That will close the WebSocket connection from the client, and Sarus will not attempt to re-establish the connection, as the WebSocket connection closure is intentional.

That covers a basic use case of Sarus to handle WebSockets. There are some more advanced features of Sarus, which are worth exploring in the documentation.