-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
103 lines (90 loc) · 2.54 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
const { ApolloServer, PubSub } = require("apollo-server-express");
const { withFilter } = require("graphql-subscriptions");
const express = require("express");
const schema = require("./schema");
const { createServer } = require("http");
const { DUMMY_DATA, PORT } = require("./constants");
const units = require("./units");
const pubsub = new PubSub();
const app = express();
const httpServer = createServer(app);
const resolvers = {
Query: {
units: () => DUMMY_DATA
},
Subscription: {
unitAdded: {
subscribe: (_, variables, connection) => {
setTimeout(() => {
publishTestData({ url: variables.url });
}, 1000);
return withFilter(
() => pubsub.asyncIterator("unitAdded"),
(payload, variables) => {
return payload.unitAdded.url === variables.url;
}
)(_, variables, connection);
}
}
}
};
const server = new ApolloServer({
typeDefs: schema,
resolvers
});
server.applyMiddleware({ app, path: "/graphql" });
server.installSubscriptionHandlers(httpServer);
httpServer.listen(PORT, () => {
console.log(
`🚀 Server ready at http://localhost:${PORT}${server.graphqlPath}`
);
console.log(
`🚀 Subscriptions ready at ws://localhost:${PORT}${
server.subscriptionsPath
}`
);
});
/*
TODO
[] Optimize memory usage
*/
const generateRandomType = () =>
Math.random() > 0.66 ? "info" : Math.random() > 0.33 ? "warning" : "okay";
const publishTestData = ({ url }) => {
/*
`url` contains all input from a form
Example value:
http://123.2.2.2/51582/EBS#Elbrus
*/
let countOfUnitsPassed = 0;
const countOfUnitsAll = units.length;
const SUBSCRIPTION_NAME = "unitAdded";
units.forEach(async unit => {
const { title, run } = unit;
let payload = {};
try {
const responseFromUnit = await run({ url });
countOfUnitsPassed++;
payload[SUBSCRIPTION_NAME] = {
id: Date.now(),
url,
status: countOfUnitsPassed === countOfUnitsAll ? "resolved" : "pending",
type: responseFromUnit.error ? "error" : generateRandomType(),
title,
description: responseFromUnit.result,
details: responseFromUnit.details
};
} catch (e) {
countOfUnitsPassed++;
payload[SUBSCRIPTION_NAME] = {
id: Date.now(),
url,
status: countOfUnitsPassed === countOfUnitsAll ? "resolved" : "pending",
type: "error",
title,
description: "ERROR"
};
}
pubsub.publish(SUBSCRIPTION_NAME, payload);
});
};