-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
server.js
281 lines (245 loc) · 8 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
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
const express = require("express");
const http = require("http");
const pg = require("pg");
const path = require("path");
const { ApolloServer } = require("apollo-server-express");
const { makeSchemaAndPlugin } = require("postgraphile-apollo-server");
const { ApolloLogPlugin } = require("apollo-log");
const cors = require("cors");
const util = require("util");
const multer = require("multer");
const fs = require("fs");
const servicesModule = require("./src/modules/services");
const exec = util.promisify(require("child_process").exec);
const { services } = servicesModule;
const upload = multer({ dest: `${__dirname}/public/uploads/` });
// EXPRESS SERVER + CORS
const app = express();
app.use(express.static("dist"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
// DYNAMIC SERVER SWITCHING
app.post("/newServer", (req, res) => {
console.log("inside the /newServer route");
console.log(req.body);
// please note - logging services on the backend will not be accurate!
// console.log(services);
createNewApolloServer(req.body)
.then((data) => myServers.push(data))
.catch((err) => console.log(err));
});
app.post(
"/uploadFile",
upload.single("myFile"),
(req, res, next) => {
// console.log("FILE", req.file);
// console.log("BODY", req.body);
fs.renameSync(
req.file.destination + req.file.filename,
req.file.destination + req.file.originalname
);
// req.file.filename = req.file.originalname;
req.fileExtension = req.file.originalname.slice(-4);
req.p = req.file.destination + req.file.originalname;
req.label = JSON.stringify(req.body).slice(26, -2);
next();
},
async (req, res, next) => {
const promisify = async (cmd) => {
try {
const { stdout, stderr } = await exec(cmd);
// console.log("stdout:", stdout);
// console.log("stderr:", stderr);
} catch (e) {
console.error(e);
}
};
await promisify(`createdb -U postgres '${req.label}'`);
if (req.fileExtension === ".sql") {
await promisify(`psql -U postgres -d ${req.label} < '${req.p}'`);
} else if (req.fileExtension === ".tar") {
await promisify(`pg_restore -U postgres -d ${req.label} < '${req.p}'`);
}
next();
},
async (req, res, next) => {
const port = services[services.length - 1].port + 1;
const newServiceFromFile = {
label: req.label,
db_uri: `postgres:///${req.label}`,
port: port,
fromFile: req.file.originalname,
};
services.push(newServiceFromFile);
console.log("new service", newServiceFromFile);
createNewApolloServer(newServiceFromFile).then((result) =>
myServers.push(result)
);
res.locals.service = newServiceFromFile;
res.status(200).json(res.locals.service);
}
);
app.delete("/deleteServer/:port", (req, res) => {
// console.log("***IN DELETE****");
console.log(services);
const myPort = req.params.port;
// console.log('myPort', myPort);
const connectionKey = `6::::${myPort}`;
myServers.forEach(async (server) => {
if (myPort == 4000) {
console.log(
"You may not close port 4000. Graphiql must be provided an active GraphQL API (of which there will always be one running on 4000)"
);
} else if (server._connectionKey == connectionKey) {
console.log(`server on ${myPort} is about to be shut down`);
await server.close();
} else {
console.log("nothing got hit!");
}
});
// console.log(services);
services.forEach(async (service, index) => {
console.log("in the loop", service.port);
if (service.port == myPort) {
if (service.fromFile) {
try {
const { stdout, stderr } = await exec(
`dropdb -U postgres ${service.label};`
);
console.log(stdout);
console.log(stderr);
} catch (e) {
console.error(e);
}
try {
fs.unlinkSync(
path.resolve(__dirname, `./public/uploads/${service.fromFile}`)
);
// console.log('FILE REMOVED')
} catch (err) {
console.error(err);
}
}
}
});
console.log(services);
});
// REDIS
const {
redisController,
cachePlugin,
updater,
} = require("./redis/redis-commands");
// SOCKET.IO
const server = http.createServer(app);
const socketIo = require("socket.io")(server, {
cors: {
origin: "*",
methods: ["GET", "POST", "DELETE"],
},
});
const getApiAndEmit = (socket) => {
// console.log(updater);
const response = updater;
socket.emit("FromAPI", response);
};
let interval;
socketIo.on("connection", (socket) => {
console.log("New client connected");
if (interval) {
clearInterval(interval);
}
interval = setInterval(() => getApiAndEmit(socket), 1000);
socket.on("disconnect", () => {
console.log("Client disconnected");
clearInterval(interval);
});
});
server.listen(3333, () => {
console.log("Success!");
});
// APOLLO SERVER + POSTGRAPHILE
// We need some logic in here to handle if the string is malformed. App crashes otherwise.
const createNewApolloServer = (service) => {
const pgPool = new pg.Pool({
// do this via an environment variable
connectionString: service.db_uri,
});
async function startApolloServer() {
const app = express();
const { schema, plugin } = await makeSchemaAndPlugin(
pgPool,
"public", // PostgreSQL schema to use
{
// PostGraphile options, see:
// https://www.graphile.org/postgraphile/usage-library/
// watchPg: true,
graphiql: true,
graphlqlRoute: "/graphql",
// These are not the same!
// not using the graphiql route below
graphiqlRoute: "/test",
enhanceGraphiql: true,
}
);
const options = {};
const server = new ApolloServer({
schema,
plugins: [plugin, cachePlugin, ApolloLogPlugin(options)],
tracing: true,
introspection: true,
});
await server.start();
server.applyMiddleware({ app });
app.use(express.json());
app.use(
express.urlencoded({
extended: true,
})
);
const corsOptions = {
origin: "*",
optionsSuccessStatus: 200,
};
app.use(cors(corsOptions));
// REDIS CACHED METRICS
app.get("/redis/:hash", redisController.serveMetrics, (req, res) => {
console.log("Result from Redis cache: ");
console.log(res.locals.metrics);
return res.status(200).send(res.locals.metrics);
});
// EXPRESS UNKNOWN ROUTE HANDLER
app.use("*", (req, res) => res.status(404).send("404 Not Found"));
// EXPRESS GLOBAL ERROR HANDLER
app.use((err, req, res, next) => {
console.log(err);
return res.status(500).send("Internal Server Error ", err);
});
const myApp = app.listen({ port: service.port });
console.log("\x1b[32m", ` .:: :: .:::: .:: `);
console.log("\x1b[32m", `.:: .:: .:: .:: .:: .: `);
console.log("\x1b[32m", ` .:: .: .:: .:: .:: .::.:: .:: .:: `);
console.log("\x1b[32m", ` .:: .: .:: .: .:: .:: .::.:: .:: .: `);
console.log("\x1b[32m", ` .:: .: .::.::::: .::.:: .::.:: .:: .: `);
console.log("\x1b[32m", `.:: .::.:: .:: .: .:: .: .:: .:: .:: .::`);
console.log("\x1b[32m", ` .:: :: .:: .:::: .:: :: .:::::::: .:::: `);
console.log("\x1b[32m", ` .:: .: `);
console.log("\x1b[35m", `Port ${service.port} active`);
console.log("\x1b[35m",
`🔮 Fortunes being told at http://localhost:3333 ✨`);
return myApp;
}
// CALL APOLLO SERVER FOR GRAPHIQL
return startApolloServer().catch((e) => {
console.error(e);
// process.exit(1);
});
};
// NEW APOLLO SERVER PER SCHEMA
const myServers = [];
services.forEach((service) => {
createNewApolloServer(service)
.then((data) => myServers.push(data))
.catch((err) => console.log(err));
});