configurapi-handler-ws
Configurapi request handlers for websocket
Usage
Server side:
- If you want to stream data back to the client, return a
StreamResponse with a readable stream.
- Use postbackFunction(postbackFunction: Function, response: PostbackResponse) to send a response to the postback endpoint. The response will be wrapped in the specified postbackFunction.
const { postbackFunction, PostbackResponse } = require("configurapi-handler-ws");
let callback = async (body:any, headers:Record<string,string>) =>
{
const isStream = body && typeof body === 'object' && typeof body.pipe === 'function';
const isBinary = typeof body === 'string' || Buffer.isBuffer(body) || body instanceof Uint8Array;
let resp = await fetch(`http://localhost:9100/@connections/${connectionId}`, {
method: 'POST',
headers,
body: isStream || isBinary ? body : JSON.stringify(body),
...(isStream ? { duplex: 'half' } : {})
});
console.log(resp.status + ' ' + resp.statusText)
console.log(await resp.json())
}
await postbackFunction(callback, new PostbackResponse('body', {'content-type': 'application/json'}))
Client side:
- Use WebSocketClient to connect to a WebSocket runner, send data over the connection, and disconnect from the runner when finished.
- To pass data (such as a protocol or authentication token) when establishing the WebSocket connection, provide it as the second parameter to the constructor.
- If a connection could not be made (e.g. the on_connect route returns 400+ status code), an error will be sent to onPush().
- The client has a default timeout of 27 seconds. To increase the wait time for results, set the
replyTimeoutMs parameter in the constructor's second argument.
const { WebSocketClient } = require("configurapi-handler-ws");
let client = new WebSocketClient(WEBSOCKET_BASE_URL, {replyTimeoutMs: 300000, onPush: (data:IResponse)=>console.log(data)});