This plugin adds fx.ws(...) to connect a WebSocket.
import { Fexios } from 'fexios'
import { pluginWebSocket } from 'fexios/plugins'const fx = new Fexios({ baseURL: 'https://example.com' }).plugin(
pluginWebSocket
)
const ws = await fx.ws('/ws', {
query: { token: 'xxx' },
timeout: 10_000,
})
ws.addEventListener('message', (event) => {
console.log('message:', event.data)
})- Returns:
Promise<WebSocket>(resolves after the socket is opened) - options.protocols: WebSocket sub-protocols passed to
new WebSocket(url, protocols) - options.query: query params to merge into the URL
- options.timeout: connect timeout in ms (default:
fx.baseConfigs.timeout ?? 60000)
- If
urlishttp(s)://..., it is converted tows(s)://... - If
urlis a relative path, it is resolved againstfx.baseConfigs.baseURL(and converted to ws/wss)
The plugin emits the following Fexios lifecycle events:
websocket:beforeConnect— allow you to modify{ url, protocols, timeout }before connectingwebsocket:openwebsocket:messagewebsocket:errorwebsocket:close
In Node.js, WebSocket may not be available globally. You can provide a polyfill (example using ws):
import WebSocket from 'ws'
;(globalThis as any).WebSocket = WebSocket as any