82 lines
2.3 KiB
JavaScript
82 lines
2.3 KiB
JavaScript
const fastify = require('fastify')({ logger: true });
|
|
const axios = require('axios');
|
|
|
|
// SSE proxy endpoint
|
|
fastify.get('/api/proxy/sse/events/orders/:orderId', async (request, reply) => {
|
|
try {
|
|
// Get the order ID from the request parameters
|
|
const orderId = request.params.orderId;
|
|
|
|
// Get the auth header from the request
|
|
const authHeader = request.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}`;
|
|
|
|
fastify.log.info(`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
|
|
reply.header('Content-Type', 'text/event-stream');
|
|
reply.header('Cache-Control', 'no-cache');
|
|
reply.header('Connection', 'keep-alive');
|
|
|
|
// Copy other headers from the response
|
|
for (const [key, value] of Object.entries(response.headers)) {
|
|
if (key.toLowerCase() !== 'content-length') {
|
|
reply.header(key, value);
|
|
}
|
|
}
|
|
|
|
// Send the response
|
|
reply.send(response.data);
|
|
|
|
// Handle client disconnect
|
|
request.raw.on('close', () => {
|
|
fastify.log.info(`Client disconnected from SSE for order ${orderId}`);
|
|
response.data.destroy();
|
|
});
|
|
} catch (error) {
|
|
fastify.log.error('Error in SSE proxy:', error);
|
|
reply.status(500).send({ error: 'Internal server error' });
|
|
}
|
|
});
|
|
|
|
// Start the server
|
|
const start = async () => {
|
|
try {
|
|
await fastify.listen({ port: 3000 });
|
|
fastify.log.info(`SSE proxy server listening at http://localhost:3000`);
|
|
} catch (err) {
|
|
fastify.log.error(err);
|
|
process.exit(1);
|
|
}
|
|
};
|
|
|
|
start();
|