79 lines
2.2 KiB
JavaScript
79 lines
2.2 KiB
JavaScript
const express = require('express');
|
|
const axios = require('axios');
|
|
const app = express();
|
|
const port = 3000;
|
|
|
|
// Middleware to parse JSON
|
|
app.use(express.json());
|
|
|
|
// SSE proxy endpoint
|
|
app.get('/api/proxy/sse/events/orders/:orderId', async (req, res) => {
|
|
try {
|
|
// Get the order ID from the request parameters
|
|
const orderId = req.params.orderId;
|
|
|
|
// Get the auth header from the request
|
|
const authHeader = req.headers['x-signed-auth'];
|
|
|
|
// API base URL
|
|
const apiBaseUrl = process.env.API_ENDPOINT || 'https://api.example.com';
|
|
|
|
// Target URL
|
|
const targetUrl = `${apiBaseUrl}/events/orders/${orderId}`;
|
|
|
|
console.log(`Proxying SSE request to: ${targetUrl}`);
|
|
|
|
// Create headers for the proxy request
|
|
const headers = {
|
|
'Accept': 'text/event-stream',
|
|
'Cache-Control': 'no-cache',
|
|
};
|
|
|
|
// Add auth header if available
|
|
if (authHeader) {
|
|
headers['X-Signed-Auth'] = authHeader;
|
|
}
|
|
|
|
// Make the request to the target URL
|
|
const response = await axios({
|
|
method: 'GET',
|
|
url: targetUrl,
|
|
headers,
|
|
responseType: 'stream',
|
|
// Skip SSL certificate validation for development
|
|
...(process.env.NODE_ENV === 'development' && {
|
|
httpsAgent: new (require('https').Agent)({ rejectUnauthorized: false })
|
|
})
|
|
});
|
|
|
|
// Set headers for SSE
|
|
res.setHeader('Content-Type', 'text/event-stream');
|
|
res.setHeader('Cache-Control', 'no-cache');
|
|
res.setHeader('Connection', 'keep-alive');
|
|
|
|
// Copy other headers from the response
|
|
for (const [key, value] of Object.entries(response.headers)) {
|
|
if (key.toLowerCase() !== 'content-length') {
|
|
res.setHeader(key, value);
|
|
}
|
|
}
|
|
|
|
// Pipe the response stream to the client
|
|
response.data.pipe(res);
|
|
|
|
// Handle client disconnect
|
|
req.on('close', () => {
|
|
console.log(`Client disconnected from SSE for order ${orderId}`);
|
|
response.data.destroy();
|
|
});
|
|
} catch (error) {
|
|
console.error('Error in SSE proxy:', error);
|
|
res.status(500).json({ error: 'Internal server error' });
|
|
}
|
|
});
|
|
|
|
// Start the server
|
|
app.listen(port, () => {
|
|
console.log(`SSE proxy server listening at http://localhost:${port}`);
|
|
});
|