-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
153 lines (129 loc) · 4.62 KB
/
app.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
const dotenv = require("dotenv");
const env = dotenv.config();
if (env.error) {
throw new Error("Failed to load the .env file!");
}
const mongoose = require("mongoose");
const express = require("express");
const cors = require("cors");
const socket = require("socket.io");
/// node-cron for task scheduling
const cron = require("node-cron");
const getNewPrompt = require("./utils/getDailyPrompt");
// create routes
const usersRouter = require('./routes/users-routes')
const quotesTipsRouter = require('./routes/quotes-tips-routes')
const postsRouter = require('./routes/posts-routes')
const commentsRouter = require('./routes/comments-routes')
const reactionsRouter = require('./routes/reactions-routes');
const meditationRouter = require('./routes/meditation-routes')
const chatsRouter = require("./routes/chats-routes");
const messagesRouter = require("./routes/messages-routes");
const spotifyRouter = require('./routes/spotify-routes')
const voiceRouter = require("./routes/voice-routes");
const cloudinaryRouter = require('./routes/cloudinary-routes');
const { generatePrompt } = require("./utils/apis/openaiUtils");
const promptResponseRouter = require("./routes/prompt-response-routes");
const matchUserRouter = require("./routes/match-user-routes");
const { fetchMatchPairs } = require("./controllers/match-user-controller");
// create express app
const app = express();
// middleware: parse incoming JSON data
app.use(
cors({
origin: "*",
})
);
app.use(express.json());
// test route to check if backend is connected
app.get("/", (req, res) => {
res.status(200).json({ message: "Connected to Backend!" });
});
// use routes
app.use('/api/users', usersRouter);
app.use('/api/posts', postsRouter);
app.use('/api/comments', commentsRouter)
app.use('/api/reactions', reactionsRouter)
app.use('/api/quotestips', quotesTipsRouter)
app.use('/api/meditation', meditationRouter)
app.use("/api/chats", chatsRouter);
app.use("/api/messages", messagesRouter);
app.use('/api/spotify', spotifyRouter)
app.use('/api/cloudinary', cloudinaryRouter)
app.use('/api/promptResponses', promptResponseRouter)
app.use('/api/matchUsers', matchUserRouter)
//app.use('/api/voice', voiceRouter)
/// Get daily prompt
/// For final results, set to "0 0 * * * " (run at every 00:00).
/// Currently runs every 15 minutes for better testing
// Check if the environment is not test
if (process.env.NODE_ENV !== 'test') {
cron.schedule("0 */15 * * *", () => {
generatePrompt();
});
}
// Get Matching Pairs at 8pm everyday
// cron.schedule('14 18 * * *', () => {
// fetchMatchPairs();
// });
// For developing purposes, run every 5 seconds
// cron.schedule("*/5 * * * * *", () => {
// generatePrompt()
// })
const onlineUsers = new Set();
// connect to MongoDB
const MONGO_URI = process.env.MONGO_URI;
if (process.env.NODE_ENV !== 'test') {
mongoose
.connect(MONGO_URI)
.then(() => {
const server = app.listen(process.env.PORT || 4000);
console.log("Connected to DB and listening on port 4000");
// Socket
// Socket setup (server)
const io = socket(server, {
cors: {
origin: "*",
methods: ["GET", "POST"],
},
});
io.on("connection", (socket) => {
console.log("Connected to socket.io");
socket.on("setup", (userData) => {
socket.join(userData._id);
socket.emit("connected");
onlineUsers.add(userData._id);
io.emit('onlineUsers', Array.from(onlineUsers));
console.log(userData.username + " joined Room: " + userData._id);
});
socket.on('userConnected', (userId) => {
onlineUsers.add(userId);
io.emit('updateUserStatus', { userId, status: 'online' });
});
socket.on("join chat", (room) => {
socket.join(room);
console.log("User Joined Room: " + room);
});
socket.on("typing", (room) => socket.in(room).emit("typing"));
socket.on("stop typing", (room) => socket.in(room).emit("stop typing"));
socket.on("new message", (newMessageRecieved) => {
var chat = newMessageRecieved.chat;
if (!chat.users) return console.log("chat.users not defined");
// socket.in(chat._id).emit("message received", newMessageRecieved);
chat.users.forEach((user) => {
if (user._id == newMessageRecieved.sender._id) return;
socket.in(user._id).emit("message received", newMessageRecieved);
});
});
socket.off("setup", (userId) => {
console.log("USER DISCONNECTED");
io.emit('updateUserStatus', { userId, status: 'offline' });
socket.leave(userId);
});
});
})
.catch((error) => {
console.log(error);
});
}
module.exports = app;