-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
113 lines (100 loc) · 2.5 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
require("dotenv").config();
const express = require("express");
const morgan = require("morgan");
const cors = require("cors");
const chalk = require("chalk");
const Socket = require("socket.io");
const bodyParser = require("body-parser");
const { greenBright, black, redBright } = require("chalk");
const routes = require("./routes");
const { getNearestHurdle } = require("./utilities/maputilities");
const report = require("./database/models/report");
const { PORT, ISDEV } = require("./utilities/constants");
//all the middlewares
require("./database");
const app = express();
app.use(cors());
app.use(morgan("tiny"));
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: true,
})
);
app.use(express.static("public"));
app.use("/api/v1", routes);
// error handler
app.get("/", (req, res, next) => {
res.send({
res: true,
msg: "Server running",
});
});
const server = app.listen(PORT, () => {
console.clear();
console.log(
chalk.bgCyanBright(
black(
` Server started on PORT ${PORT} at ${Date()} as ${
ISDEV ? "DEV" : "PRODUCTION"
}\n`
)
)
);
});
const io = Socket(server);
let clients = [];
const getClientById = (id) => {
for (const client of clients) {
if (client.id === id) {
return client;
}
}
};
const addClient = (client) => {
clients.push(client);
console.log(greenBright(`USER ${client.id} joined!`));
};
const removeClient = (client) => {
clients.splice(clients.indexOf(client), 1);
console.log(chalk.redBright(`User ${client.id} left`));
};
io.sockets.on("connection", (soc) => {
addClient(soc);
soc.on("disconnect", () => {
removeClient(soc);
});
addEvents(soc);
});
const addEvents = (client) => {
client.on("GET_HURDLE", ({ coords, id, lastDist }) => {
report
.find({})
.then((docs) => {
const hurdle = getNearestHurdle(coords, docs);
if (
hurdle.distance > lastDist &&
hurdle.hurdle &&
String(hurdle.hurdle._id) === String(id) &&
id
) {
client.emit("LE_HURDLE", {
hurdle: { _id: id },
distance: lastDist,
});
} else {
client.emit("LE_HURDLE", hurdle);
}
})
.catch(console.error);
});
};
app.use(function (err, req, res, next) {
console.log(redBright(err.stack));
res
.send({
msg: ISDEV ? err.message : "Contact Developer",
stack: ISDEV ? err.stack : "Error stack not visible on production",
})
.status(500);
});