Sends a type-safe, validated message using a message definition.
This is the preferred way to send messages as it provides:
The message definition type
Message definition created with defineMessage()
Message data that matches the definition's schema
const userMsg = defineMessage('user', z.object({
name: z.string(),
age: z.number().min(0)
}));
// Type-safe and validated
await channel.sendMessage(userMsg, {
name: 'Alice',
age: 25
});
// TypeScript error: missing required field
await channel.sendMessage(userMsg, { name: 'Bob' }); // Error!
// Runtime error: validation fails
await channel.sendMessage(userMsg, { name: 'Charlie', age: -1 }); // Throws!
Registers a message handler for a specific message type (by string ID).
String identifier for the message type
Function to handle incoming messages
Registers a type-safe message handler using a message definition. This is the preferred method as it provides full type safety.
Message definition created with defineMessage()
Type-safe handler function
Removes a message handler for a specific message type (by string ID).
String identifier for the message type
The exact handler function to remove
Removes a type-safe message handler using a message definition.
Message definition created with defineMessage()
The exact handler function to remove
Establishes a WebSocket connection using the Node.js 'ws' library.
Optimized for server environments with enhanced error reporting and automatic reconnection handling.
WebSocket server URL (ws:// or wss://)
Closes the connection and cleans up resources.
Sends raw data over the channel. Use sendMessage() for type-safe validated sending instead.
Message type identifier
Raw message data
Configures automatic reconnection behavior for Node.js environments.
Particularly useful for microservices and server applications that need high reliability and resilience to network issues.
Maximum number of reconnection attempts (default: 5)
Initial delay in milliseconds (default: 1000)
Example
Basic server usage:
Example
Microservice communication: