Blog>
Snippets

Setting Up Real-Time Data Synchronization

Demonstrate the process of setting up real-time data synchronization between RAG components and SQL databases using web sockets or long polling.
<div id="realtime-data-container"></div>
HTML markup for the container where real-time data will be displayed.
#realtime-data-container {
    /* CSS styling for real-time data container */
    border: 1px solid #ddd;
    padding: 10px;
    margin-top: 10px;
}
CSS styling that gives a border and padding to the real-time data container, making it visually distinguishable.
const socket = new WebSocket('wss://your-websocket-server.com/data');

// Listen for messages
socket.addEventListener('message', function (event) {
    const data = JSON.parse(event.data);
    updateUI(data);
});

// Function to update UI with new data
function updateUI(data) {
    const container = document.getElementById('realtime-data-container');
    container.textContent = data.value;
}
JavaScript code that creates a WebSocket connection to the server and listens for messages. When a message is received, it parses the JSON data and updates the UI.
setInterval(function(){
    fetch('https://your-long-polling-server.com/data')
        .then(response => response.json())
        .then(data => updateUI(data))
        .catch(err => console.error('Long polling error:', err));
}, 5000);

function updateUI(data) {
    const container = document.getElementById('realtime-data-container');
    container.textContent = data.value;
}
JavaScript code that sets up long polling. It makes a request to the server every 5 seconds and updates the UI with the received data. This is an alternative to WebSockets for real-time data synchronization.