// Connect to the serverawait client.connect();// Check connection statusconst isConnected = client.isConnected();console.log('Connected:', isConnected);// Get connection statusconst status = client.getConnectionStatus();console.log('Status:', status); // 'connected', 'connecting', 'disconnected', etc.
Subscribe to a channel/topic to receive real-time messages:
Copy
// Create or get a channelconst channel = client.realtime.channel('my-topic');// Subscribe to messagesconst unsubscribe = channel.stream((message, metadata) => { console.log('Message:', message); console.log('Metadata:', metadata); // Metadata contains: // - offset: Message sequence number // - timestamp: When message was sent // - replay: Boolean indicating if this is a replayed message // - channel: Channel name});// Later, unsubscribe when doneunsubscribe();
Every message comes with metadata that provides context:
Copy
channel.stream((message, metadata) => { console.log('Message data:', message); // Metadata structure const { offset, // Number: Message sequence in the channel timestamp, // String: ISO timestamp when message was sent replay, // Boolean: true if this is a missed message being replayed channel // String: Channel name } = metadata; if (metadata.replay) { console.log('This is a replayed message from offset:', metadata.offset); }});
Publish messages via HTTP when WebSocket is not available:
Copy
const client = new Brook({ apiKey: 'your-api-key' });// Publish via HTTP// Note: Origin header is automatically sent by browsersconst result = await client.publishHttp('my-topic', { text: 'Hello from HTTP!'});console.log('Published:', result);
import axios from 'axios';const response = await axios.post( 'https://connect.aptly.cloud/realtime', { channel: 'my-topic', message: { text: 'Hello from axios!' } }, { headers: { 'Content-Type': 'application/json', 'x-api-key': 'your-api-key', 'Origin': 'https://your.allowed.website' // Note: In browsers, Origin header is automatically sent and you don't need to specify it } });console.log('Published:', response.data);
Monitor connection status changes to handle reconnections and errors:
Copy
// Subscribe to connection changesconst unsubscribe = client.onConnectivityChange((status) => { console.log('Connection status changed to:', status); switch(status) { case 'connected': console.log('Connected and ready to send/receive messages'); break; case 'connecting': console.log('Attempting to connect...'); break; case 'reconnecting': console.log('Connection lost, attempting to reconnect...'); break; case 'disconnected': console.log('Disconnected from server'); break; case 'failed': console.log('Connection failed'); break; }});// Unsubscribe when doneunsubscribe();