# @qrvey/websocket-client

![install size](https://packagephobia.com/badge?p=@qrvey/websocket-client)


The `@qrvey/websocket-client` package provides a unified interface to work with websocket as any client. Works from Backend and Frontend.
This package is based on the WebSocket services that use Socket.io

# Installation

```bash
npm install @qrvey/websocket-client
```

Or with yarn:

```bash
yarn add @qrvey/websocket-client
```

# Environment variables

```javascript
DOMAIN; // The BASE Qrvey domain. If not set, could be pass in the constructor of WebSocketClient class
```

# API Documentation

## Class: WebSocketClient

### Constructor

#### `new WebSocketClient(auth, options)`

Creates an instance of `WebSocketClient`.

- **Parameters:**
  - `auth` (Object): Authentication details.
    - `userId` (string, optional): User identifier.
    - `clientId` (string, optional): Client identifier.
    - `token` (string, optional): Authentication token.
    - `apiKey` (string, optional): API key.
  - `options` (Object): Additional options.
    - `domain` (string, optional): Domain to stablish connection with the socket. If not set, try to find the domain in `process.env.DOMAIN`
    - `isAutoPingPongEnable` (boolean, optional, default=true): Enables or disables the auto ping-pong mechanism.

### Methods

#### `publish({ eventName, data, isPublic = false }: { eventName: string; data: Record<string, any>; isPublic?: boolean; }): void`

Publishes an event with the specified data.

- **Parameters:**
  - `eventName` (string): The name of the event to publish.
  - `data` (any): The data to send with the event.
  - `isPublic` (boolean, optional, default=false): Whether the event is public or not.

#### `subscribe(eventName: string, callback: (message: any) => void): void`

Subscribes to an event and provides a callback to handle the messages.

- **Parameters:**
  - `eventName` (string): The name of the event to subscribe to.
  - `callback` (function): A callback function to handle the messages. The function receives one argument:
    - `message` (any): The message received from the event.

- **Returns:** this (the instance of WebSocketClient)

#### `onError(callback: (message: any) => void): void`
Sets a callback function to handle error messages.

- **Parameters:**
    - `callback` (function): A callback function to handle error messages. The function receives one argument:
      - `message` (any): The error message.

#### `status(): SOCKET_STATUS`

Returns the current status of the WebSocket connection.

- **Returns:** SOCKET_STATUS (enum): The current status of the WebSocket connection.

#### `connect(): void`

Establishes the WebSocket connection if needed. After create the instances, the connection and reconnection is done by default.

#### `disconnect(): void`

Disconnects the WebSocket client.

## Enum: SOCKET_STATUS

The `SOCKET_STATUS` enum defines the possible states of a WebSocket connection.
 
**Enum Values:**
  - `CONNECTED`: Indicates that the WebSocket connection has been successfully established.
  - `ACTIVE`: Indicates that the WebSocket connection is active and currently transmitting or receiving data.
  - `RECOVERED`: Indicates that the WebSocket connection was lost but has been successfully re-established.
  - `DISCONNECTED`: Indicates that the WebSocket connection has been intentionally or unintentionally closed.
  - `UNDEFINED`: Indicates that the WebSocket connection status is undefined or has not yet been determined.

# Usage Example

```javascript
const { WebSocketClient, SOCKET_STATUS }  = require('@qrvey/websocket-client');

const socket = new WebSocketClient({ userId: '', token: '' });

socket.publish({
    eventName: 'from:example',
    data: { body: 'example message' }
})

socket.subscribe('example', (message) => {
    console.log('Recibed: ', message);
})

if (socket.status() === SOCKET_STATUS.DISCONNECTED) console.log('Socket disconnected!')

```