Code Samples

Subscribe to all stream posts you follow

import * as ws from 'ws';

const WS_API_ENDPOINT = 'wss://api.synoptic.com/v1/ws';
const API_KEY = 'YOUR_API_KEY';

let client: ws.WebSocket | null = null;
const RECONNECT_DELAY_MS = 5000;

function connect() {
    client = new ws.WebSocket(
        `${WS_API_ENDPOINT}/on-stream-post?apiKey=${API_KEY}`,
    );

    client.onopen = () => {
        console.log('Connected to the server');
        // Connection established
    };

    client.onmessage = (event) => {
        console.log('Received message:', event.data);
        // TODO: Handle incoming messages
    };

    client.onerror = (error) => {
        console.error('WebSocket error:', error);
        // Reconnect on error
        cleanupAndReconnect();
    };

    client.onclose = () => {
        console.log('WebSocket connection closed');
        // Reconnect on close
        cleanupAndReconnect();
    };
}

function cleanupAndReconnect() {
    if (client) {
        client.removeAllListeners();
        client = null;
    }
    setTimeout(connect, RECONNECT_DELAY_MS);
}

connect();

Last updated