@gigachatpl/action-based-websocket
TypeScript icon, indicating that this package has built-in type declarations

1.1.4 • Public • Published

ActionBasedWebSocket is a class that wraps WebSocket (default browser WebSocket or from the WS library) and communicates with the server using JSON, making it easier to work with. The class allows for authorization, automatic server reconnection, and communication based on actions.

ActionBasedWebSocket

ActionBasedWebSocket requires three types to work:

Action

An enum that contains action names, which are equivalent to event names in JavaScript.

enum action {
    GET_DATA = "get",
    SEND_DATA = "send"
}

Receiving types

This interface maps action names to the types received from these actions.

interface MapGivenType {
    [action.GET_DATA]: { usernames: string[] };
}

Sending types

This interface maps action names to the types sent from these actions.

interface MapSendType {
    [action.SEND_DATA]: { newData: number };
}

Creation

The constructor requires one of three types of objects. They share the same variables but have different configurations depending on the situation. For example, you don't need a connection address if you've already provided a ready WebSocket.

  • websocket -> WebSocket object (from the browser or WSToBrowser, which is part of this package).
  • websocketConstructor -> The class to be used to create a WebSocket.
  • address -> The address to which the WebSocket should connect.
  • onLostConnection -> Callback executed when the connection is lost.
  • onReconnected -> Callback executed when the connection is reestablished.
  • onAuthSuccess -> Callback is only stored.
  • onAuthFail -> Callback is only stored.
  • is_reconnect -> Indicates whether the WebSocket connection should be re-established in case of loss. Default is false.
  • actionWithoutAuthorization -> Array of actions that can be executed without authorization.
  • actionBasedServer -> an instance of actionBasedServer that hosts a websocket. Example:
new ActionBasedWebSocket<action, MapGivenType, MapSendType>({ websocket: new Websocket("ws:localhost:3000") })

Method: log

The entire class uses the log method for logging, which by default uses console.log().

Method: oninit

The oninit method is executed at the beginning of the constructor. It's initially empty (only logs that it's executed).
It can be used, for example, to override properties by a inheriting class before the rest of the constructor is executed.

Method: oncreate

The oncreate method is executed at the beginning of the constructor after the oninit method. It's initially empty (only logs that it's executed).
It can be used, for example, to set up responseHandlers.

Method: onopen

It is set as the onopen property of the WebSocket. Additionally, if a ready WebSocket was passed to the constructor, the onopen method will be executed in the constructor. It's initially empty (only logs that it's executed).

Method: send

Sends an action.

  • action -> The action name.
  • params -> Data to be sent. Type checking is performed based on the previously specified types.
  • onsuccess -> Callback executed when a response without errors is received. The first parameter is an object of the type defined in the previously specified types.
  • onerror -> Callback executed when an error response is received.

Method: addResponseHandler

Allows adding a responseHandler, similar to using addEventListener in JavaScript. If a specific action is received, the provided callback is executed.

  • action -> The action name.
  • fun -> The callback to be executed for the specified action. It performs type checking for both parameters and return values. The value returned in the callback will be sent as a response. Example:
actionBasedWebSocket.addResponseHandler(action.ADD_ONE, (params) => {
    return { result: params.number + 1 };
})

The method returns a function that can be used later to remove the responseHandler.

Method: removeResponseHandler

Removes a specific callback from the responseHandler.

  • action -> The action name.
  • fun -> The function returned from addResponseHandler. removeAllResponseHandlers: Removes all callbacks for a specific action.
  • action -> The action name.

Authorization

The default connected WebSocket is not authorized. This means that any action that comes in (except those listed in actionWithoutAuthorization) will result in an authorization error. To authorize all actions, you should use the authorizeAllRequests method. This allows, for example, to expose one action for logging in, while the rest will only be accessible after logging in.

Error Handling

If an error occurs during the execution of a action's callback, the recipient will receive an "Internal Error" message.
An exception is the PublicError class from this package, which allows sending error messages to the recipient. In this case, the error handling callback will be triggered.

PublicError takes two parameters: the error message and the error code.

Example:

throw new PublicError("Data is incorrect", 402);

ActionBasedServer

This is a class that inherits from WebSocketServer WS. It adds methods for sending actions to clients.

Method: registerClient

Allows registering a client under a specific ID.

Method: unregisterClient

Allows unregistering a client with a given ID.

Method: broadcast

Enables broadcasting actions to clients registered under a specific ID.

WSToBrowser

Although the WS library is based on the browser's WebSocket, it has a slight difference in the send method. This class, which inherits WebSocket from WS, eliminates this difference. The rest remains unchanged, and you can use it just like WebSocket from WS .

Readme

Keywords

Package Sidebar

Install

npm i @gigachatpl/action-based-websocket

Weekly Downloads

5

Version

1.1.4

License

MIT

Unpacked Size

43.9 kB

Total Files

19

Last publish

Collaborators

  • bukaj
  • vdanielv