-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
88 lines (68 loc) · 2.68 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const express = require('express');
const socketIO = require('socket.io-client');
const superagent = require('superagent');
const bodyParser = require('body-parser');
const http = require('http');
// The URI for the outGoingRouter
//turbosrc-service tells ingress the outgoing.
var outGoingRouterUri = getEgressRouterURL().replace('/graphql', '');
// The URI for the turbosrc-service
const turbosrcServiceUri = 'http://turbosrc-service:4000/graphql';
// Connect to the outGoingRouter (aka egress-router)
let socket = createSocketConnection(outGoingRouterUri);
function getTurboSrcID() {
return process.env.TURBOSRC_ID;
}
function getEgressRouterURL() {
return process.env.EGRESS_ROUTER_URL;
}
function createSocketConnection(uri) {
const turboSrcID = getTurboSrcID()
const reponame = turboSrcID + "/" + turboSrcID
const socket = socketIO(uri, {
autoConnect: true,
reconnection: true,
reconnectionDelay: 1000, // wait 1 seconds before attempting to reconnect
reconnectionAttempts: Infinity,
transports: ['websocket', 'polling'], // Add this line
secure: uri.startsWith('https'), // Add this line
rejectUnauthorized: false, // Add this line
});
socket.on('connect', () => {
console.log(`Connected to egress-router on ${uri}.`);
socket.emit('newConnection', turboSrcID, reponame);
});
socket.on('error', (error) => {
console.error(`Error occurred with egress-router: ${error.message}`);
});
socket.on('connect_error', (error) => {
console.error(`Connection error occurred with egress-router: ${error.message}`);
});
socket.on('disconnect', () => console.log('Disconnected from egress-router.'));
socket.on('reconnecting', (attemptNumber) => console.log(`Attempting to reconnect to egress-router. Attempt ${attemptNumber}`));
return socket;
}
// Start Express
const app = express();
// Use JSON body parser for GraphQL
app.use(bodyParser.json());
// Listen for messages from outGoingRouter via Socket.IO
socket.on('graphqlRequest', async ({ requestId, query, variables }) => {
console.log("send-query:", query)
try {
// Send the request to turbosrc-service via HTTP
const res = await superagent
.post(turbosrcServiceUri)
.send({ query, variables })
.set('accept', 'json');
// Forward the response back to outGoingRouter
socket.emit('graphqlResponse', { requestId, body: res.body });
} catch (error) {
// Forward the error back to outGoingRouter
socket.emit('graphqlResponse', { requestId, errors: [{ message: error.message }] });
}
});
// Start HTTP server
const server = http.createServer(app);
const port = process.env.PORT || 4005;
server.listen(port, () => console.log(`Listening on port ${port}`));