jsonrpc-ws-client v1.1.7
JSON RPC Websocket Client
Minimal websocket client library for JSON-RPC messages.
The client is designed to run in node, the browser and React Native and supports heartbeat and automatic reconnection.
Installation
yarn add jsonrpc-ws-client
Usage
Before calling remote methods wait for the open
event:
import Client from 'jsonrpc-ws-client'
const client = new Client(new WebSocket('wss://api.example.com'))
client.onopen = async () => {
const result = await client.call('Net.ping', [Date.now()])
console.log(result)
}
To send a batch request pass an array:
import Client from 'jsonrpc-ws-client'
const client = new Client(new WebSocket('wss://api.example.com'))
client.onopen = async () => {
const batch = [
client.packet('Person.read'),
client.packet('Status.get')
]
const result = await client.call(batch)
// result is an array of responses
console.log(result)
}
API
Client
Client provides a convenient API for making JSON-RPC calls to backend services.
This code needs to run in the browser and node so you must pass
a WebSocket
instance which you can get from the runtime environment.
For node require('ws')
is sufficient and in the browser or mobile you have
window.WebSocket
.
Client()
new Client(ws, options)
Client wraps a websocket and provides methods for calling remote services.
The default behaviour is to reject the promise when a server method returns an
error however for test purposes it can be preferable to return the error object
using the returnErrors
option. You should not use returnErrors
in production
code instead catch the promise rejection.
The keepalive (or heartbeat) functionality is not enabled by default. Specify an
interval in milliseconds using the keepalive
option and the client will send
a heartbeat message (the empty object {}
) to the server periodically.
Use the retry
option to enable automatic reconnection when the underlying socket
is closed.
The server can send push notifications to trigger methods on the client. For a client
to handle these notifications it needs to declare the services
option.
const services = {
Server: {
shutdown: () => {
// Handle server shutdown event
}
}
}
const client = new Client(new WebSocket('wss://api.example.com'), {services})
If the server sends parameters with a notification they are passed as an array:
const services = {
Connect: {
talk: async (params) => {
const vid = params[0]
await client.call('Call.start', [vid])
}
}
}
The options for function hooks open
, close
, error
, connect
and reconnect
allow consumers to respond to lifecycle events on the connection.
The open
, close
and error
hooks correspond to the underlying events from the
websocket. The connect
hook is invoked every time a reconnection attempt occurs and
reconnect
when a connection is re-established.
If you prefer you can add these hooks to the client after instantiation by prefixing
the hook with on
.
const opts = {open: () => console.log('websocket connection open')}
const client = new Client(new WebSocket('wss://api.example.com'), opts)
Can be written as:
const client = new Client(new WebSocket('wss://api.example.com'))
client.onopen = () => {
console.log('websocket connection open')
}
ws
Object WebSocket instance.options
Object configuration options.
Options
services
Object map of client service methods.returnErrors
Boolean=false do not reject errors return the error response.wrapErrors
Boolean=true convert error responses to Error instances.batchErrors
Boolean=true reject on first error in a batch response.keepalive
Number interval for keepalive heartbeart messages.retry
Number|Object|Boolean=false enable automatic reconnection.retry.timeout
Number=2000 interval for retry requests.retry.limit
Number=64 maximum reconnection attempts.open
Function listener for the open event.close
Function listener for the close event.error
Function listener for the error event.connect
Function listener for the connect event (reconnection attempt).reconnect
Function listener for the reconnect event (connection established).limit
Function listener for the reconnect limit event (maximum retries reached).encoder
Object=JsonEncoder encoder implementation.
Throws
TypeError
if no websocket argument is given.
url
String url
Get the underlying URL for the connection.
connected
Boolean connected
Determine if the underlying websocket is connected (open).
notify()
notify(method[, params])
Call a remote method without a response. This sends a request with a null id so the server will not reply.
Returns promise that resolves once the packet has been sent.
method
String service method name.params
Array list of method parameters.
echo()
echo(arg)
Send an echo request to the server.
This method is provided as a convenience for debugging network issues, it
calls the Net.echo
remote service method.
Returns promise that resolves once a reply is received.
arg
Object The argument to echo.
ping()
ping()
Send a ping request to the server.
This method is provided as a convenience for debugging network issues, it
calls the Net.ping
remote service method.
Returns promise that resolves once a reply is received.
packet()
packet(method[, params][, id])
Generate an RPC packet.
When no message id is given this method will assume a response is required and generate an auto-increment id for the packet.
This method is particularly useful for batch requests:
const batch = [
client.packet('Person.read'),
client.packet('Status.get')
]
const result = await client.call(batch)
Returns object RPC packet.
method
String service method name.params
Array list of method parameters.id
Number message id.
call()
call(method[, params])
Call a remote method and expect a reply.
If an array is passed as the first argument the request is treated as a batch request and each entry in the array should be a valid packet.
Provided the returnErrors
option has not been enabled the
returned promise will be rejected when the server returns an error.
Returns promise that resolves when the server replies.
method
String|Array service method name.params
Array list of method parameters.
send()
send(packet)
Send a packet.
Returns promise that resolves when the data has been sent.
packet
Object data to encode and send.
raw()
raw(payload)
Send a raw payload.
When this library is used in a node program this method will resolve the promise when all data has been flushed.
For browser usage this method resolves immediately and it is possible data is still buffered.
Returns promise that resolves when the data has been sent.
payload
String|Buffer data to send.
close()
close()
Close and destroy the underlying websocket.
destroy()
destroy()
Clean listeners and remove the underlying websocket reference.
retry()
retry()
Force a reconnection attempt when automatic reconnection is enabled and in progress.
If the retry
option was not given this method call is a noop.
replace()
replace(the)
Replace this client's websocket.
Assumes that close() has already been called on the websocket associated with this client before replace is called.
the
Object new websocket for this client.
renew()
renew()
Closes any existing websocket, creates a new websocket using
the url
assigned to this client and assigns it by calling replace.
Assumes a WebSocket was previously given so Type is set.
Throws
is
TypeError no Type is available.
JsonEncoder
Encodes and decodes to and from JSON.
This abstraction exists so we can switch to an alternative encoding if necessary.
encode()
static encode(packet)
Encode a packet to JSON.
The returned promise is rejected on encoding error.
Returns a promise that resolves once encoding is complete.
packet
Object data to encode.
decode()
static decode(packet)
Decode a packet from a JSON string.
The returned promise is rejected on decoding error.
Returns a promise that resolves once decoding is complete.
packet
String data to decode.
KeepAlive
Sends heartbeat messages over the socket at regular intervals
to keep the connection alive, a heartbeat message is the empty object: {}
.
You should not instantiate this class directly instead use the keepalive
option when creating a Client
.
KeepAlive()
new KeepAlive(client, interval)
Creates a keepalive instance.
client
Object websocket client wrapper.interval
Number=30000 milliseconds between heartbeart messages.
start()
start()
Start sending heartbeat messages.
stop()
stop()
Stop sending heartbeat messages.
Reconnect
Attempts to open a closed socket connection.
You should not instantiate this class directly instead use the retry
option when creating a Client
.
Reconnect()
new Reconnect(client[, interval][, limit])
Create a Reconnect instance.
client
Object websocket client wrapper.interval
Number=2000 milliseconds between reconnection attempts.limit
Number=64 maximum number of reconnection attempts.
retry()
retry()
Start attempting to reconnect.
If this instance is already attempting to establish a connection
this method will return false
.
Returns boolean indicating whether retry commenced.
retries
Number retries
Current number of retry attempts.
start()
start([interval])
Start attempting to reconnect.
interval
Number=1000 milliseconds before a reconnection attempt.
stop()
stop()
Stop attempting to reconnect.
Developer
npm test
Run all test specs.npm run cover
Generate code coverage.npm run build
Transpile fromsrc
tolib
.npm run lint
Lint the source tree.mk
Build the readme file.
Created by mkdoc on May 1, 2018