forked from NooksApp/nooks-fullstack-takehome
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
70 lines (62 loc) · 2.18 KB
/
index.js
File metadata and controls
70 lines (62 loc) · 2.18 KB
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
const express = require("express")
const app = express()
const server = require("http").createServer(app)
const cors = require("cors")
const mongoose = require("mongoose");
const { Session } = require("./sessionModel")
const io = require("socket.io")(server, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
})
const { updateYoutubeLink, updatePlayPause, updateTimestamp, getSession} = require("./dbHelper")
const { errorHandler, errorWrap } = require("./middleware")
const API_PORT = 9000; // TODO: keep in .env
const MONGO_URI = "mongodb+srv://dev:test@nooks.uhslfuh.mongodb.net/?retryWrites=true&w=majority" // TODO: keep in .env
app.use(express.json())
app.use(cors())
app.use(errorHandler);
const connectToDatabase = async () => {
mongoose.set("strictQuery",false)
await mongoose.connect(MONGO_URI);
console.log("Connected to the database!");
}
connectToDatabase()
io.on("connection", socket => {
console.log(`Socket connection ID: ${socket.id}`)
socket.on("join", async ({ sessionId }) => {
socket.join(sessionId)
const state = await getSession(sessionId)
io.to(socket.id).emit("state", state);
});
socket.on("switchLink", async ({ sessionId, youtubeLink }) => {
const state = await updateYoutubeLink(sessionId, youtubeLink)
io.to(sessionId).emit("linkState", state)
})
socket.on("playPause", async ({ sessionId, isPlaying, timestamp }) => {
const state = await updatePlayPause(sessionId, isPlaying, timestamp)
io.to(sessionId).emit("playState", state)
})
socket.on("seek", async ({ sessionId, timestamp }) => {
const state = await updateTimestamp(sessionId, timestamp)
io.to(sessionId).emit("timeState", state)
})
})
app.post(
"/",
errorWrap( async (req, res) => {
const { youtubeLink } = req.body
const session = await Session.create({
youtubeLink
})
res.status(200).json({
success: true,
message: "Successfully created new session!",
result: { sessionId: session._id }
})
}),
)
server.listen(API_PORT, () => {
console.log(`Server running on port ${API_PORT}!`)
})