58 lines
1.6 KiB
TypeScript

import { getSSEConnection, setupSSECleanup } from '../src';
// Set up automatic cleanup
setupSSECleanup();
// Example order tracking function
function trackOrder(orderId: string, authToken: string) {
const apiBaseUrl = 'https://api.example.com';
const sseUrl = `${apiBaseUrl}/events/orders/${orderId}`;
console.log(`Connecting to SSE endpoint: ${sseUrl}`);
// Get or create a connection for this order
const client = getSSEConnection(sseUrl, `order-${orderId}`, {
headers: {
'X-Signed-Auth': authToken
},
debug: true
});
// Listen for order state changes
client.on('orderStateChanged', (event) => {
const data = event.parsedData;
console.log('Order state changed:', data);
// Update UI with new order state
updateOrderUI(data);
// If order is ended, close the connection
if (data.currentState && data.currentState.orderStatus === 1111) {
console.log(`Order ${orderId} ended, closing SSE connection`);
client.close();
}
});
// Listen for connection errors
client.on('error', (event) => {
console.error('SSE connection error:', event.detail);
});
return client;
}
// Example function to update UI with order state
function updateOrderUI(data: any) {
// Implementation would depend on your UI framework
console.log('Updating UI with order state:', data);
}
// Example usage
const orderId = '123456';
const authToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
const connection = trackOrder(orderId, authToken);
// Later, to manually close the connection
// connection.close();