-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
85 lines (76 loc) · 2.37 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
const express = require("express");
require("dotenv").config();
const bodyParser = require("body-parser");
const cors = require("cors");
const userModel = require("./models/user");
const otpRoutes = require('./routes/otp.routes.js');
const jwt = require("jsonwebtoken");
const app = express();
const userRouter = require("./routes/user");
const { logData } = require("./controllers/user");
const http = require("http");
const socketIO = require("socket.io");
const server = http.createServer(app);
const { connectMongoDb } = require("./connection");
const io = socketIO(server, {
cors: {
origin: (origin, callback) => {
// Allow requests with no origin (like mobile apps or curl requests)
if (!origin) return callback(null, true);
// Check if the origin is allowed
const allowedOrigins = ["http://localhost:3000"];
if (allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error("Not allowed by CORS"));
}
},
methods: ["GET", "POST"],
credentials: true,
},
});
const port = 8001;
app.use(cors());
connectMongoDb(process.env.MONGO_URI);
// Configuring body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use("/user", userRouter);
// OTP API
app.use('/api/otp', otpRoutes);
// basic get request
app.get("/", async (req, res) => {
res.json({ message: "Working" });
});
//signup route
io.on("connection", (socket) => {
console.log("User connected");
socket.on("locationChange", async (data) => {
try {
const userId = jwt.verify(data.token, process.env.SECRET_KEY).userId;
const user = await userModel.findById(userId);
if (!user) {
console.log("Failure: Location not saved , User not found with id :" ,userId )
return res.status(404).json({ message: "User not found" });
}
user.latitude = data.latitude;
user.longitude = data.longitude;
user.locationUpdate = new Date();
user.save();
logData("Success", "Location Saved", {
id: user._id,
name: user.name,
email: user.email,
zealId: user.zealId,
});
} catch (error) {
console.error(error.message);
}
});
socket.on("disconnect", () => {
console.log("User disconnected");
});
});
server.listen(port, () => {
console.log(`Hello world app listening on port ${port}!`);
});