-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
126 lines (90 loc) · 2.67 KB
/
index.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
const path = require('path');
const { PORT, URL } = require('./src/constants');
// Define services
const Services = {
"Dereva": {},
"Example": {}
};
// Define apps
const Apps = [
"/",
"transaction-viewer"
];
// Configure HTTP
const http = require('http');
const express = require('express');
const cors = require('cors');
const httpApi = express();
httpApi.use(express.json({ limit: '10mb' }));
httpApi.use(express.urlencoded({ extended: false, limit: '10mb' }));
httpApi.use(cors());
const server = http.createServer(httpApi);
server.listen(PORT, () => {
// Configure WS
const socketApi = require('socket.io')(server);
// Serve HTML pages
Apps.forEach(directory => {
httpApi.use(
express.static(
path.join(__dirname, './src/apps', directory)
)
);
});
console.log(`Service "HttpApi" is online at ${URL}`);
console.log(`Service "SocketApi" is online at ${URL}`);
// Start backend services
Object.keys(Services).forEach(key => {
const serviceSlug = key.replace(/ /g, '-');
Services[serviceSlug] = require(`./src/services/${serviceSlug.toLowerCase()}`);
});
// Ping handler
httpApi.get('/', (_, res) => res.send('Services are online.'));
// Route service requests
Object.keys(Services).forEach(name => {
const slug = (
`/${name.toLowerCase().replace(/[^\w]+/g, '-')}`
);
const Service = Services[name];
if (Object.keys(Service).length) {
console.log(`Service "${name}" is online at ${URL}${slug}`);
// Handle http
if (Service.type === 'http') {
httpApi.get(`${slug}/*`, (req, res) => {
if (Object.keys(req.query).length) {
return Service.onHttpSearch(req, res);
}
return Service.onHttpGet(req, res);
});
httpApi.post(`${slug}/*`, (req, res) => (
Service.onHttpPost(req, res)
));
httpApi.put(`${slug}/*`, (req, res) => (
Service.onHttpPut(req, res)
));
httpApi.delete(`${slug}/*`, (req, res) => (
Service.onHttpDelete(req, res)
));
}
// Handle websocket
if (Service.type === 'ws') {
socketApi.on('connect', async socket => {
await Service.onWsConnect(
{
method: 'connection',
body: socket
},
socket
);
socket.on('disconnect', req => {
Service.onWsDisconnect(req, socket);
});
// eslint-disable-next-line no-magic-numbers
socket.on(`${slug.substring(1)}:request`, req => {
Service.onWsRequest(req, socket);
});
});
Service.onWsReady();
}
}
});
});