The global namespace for rockets is rocketsClient:
const{Client}= rocketsClient;
constrockets=newClient({
url:'myhost'
});
Usage
Connection
Create a client and connect:
import{Client}from'rockets-client';
constrockets=newClient({
url:'myhost',
onConnected(){
console.info('I just connected');
},
onClosed(evt){
console.log(`Socket connection closed with code ${evt.code}`);
}
});
Close the connection with the socket cleanly:
import{Client}from'rockets-client';
constrockets=newClient({url:'myhost'});
rockets.subscribe({
next(notification){
console.log(notification);
},
complete(){
console.log('Socket connection closed');
}
});
rockets.disconnect();
Notifications
Listen to server notifications:
import{Client}from'rockets-client';
constrockets=newClient({url:'myhost'});
rockets.subscribe(notification=>{
console.log(notification);
});
Send notifications:
import{Client}from'rockets-client';
constrockets=newClient({url:'myhost'});
rockets.notify('mymethod',{
ping:true
});
Send a notification using the Notification object:
import{Client,Notification}from'rockets-client';
constrockets=newClient({url:'myhost'});
constnotification=newNotification('mymethod',{
ping:true
});
rockets.notify(notification);
Requests
Make a request:
import{Client}from'rockets-client';
constrockets=newClient({url:'myhost'});
constresponse=awaitrockets.request('mymethod',{
ping:true
});
console.log(response);
NOTE: There is no need to wait for a connection to be established with the socket as requests will be buffered and sent once the connection is alive.
In case of a socket error, the request promise will reject.
The same is true for batch requests and notifications.
Or make a request using the Request object:
import{Client,Request}from'rockets-client';
constrockets=newClient({url:'myhost'});
constrequest=newRequest('mymethod',{
ping:true
});
constresponse=awaitrockets.request(request);
console.log(response);
Handle a request error:
import{Client}from'rockets-client';
constrockets=newClient({url:'myhost'});
try{
awaitrockets.request('mymethod');
}catch(err){
console.log(err.code);
console.log(err.message);
console.log(err.data);
}
NOTE: Any error that may occur will be a JsonRpcError.