-
Notifications
You must be signed in to change notification settings - Fork 4
/
app.js
92 lines (74 loc) · 2.28 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
//import environment variables
import {PORT, MONGO_URI, SECRET, TEST} from "./config.js";
import cors from "cors"
//import express
import express from "express";
//import api routers
import userApiRoute from "./routes/user_api.js"
import roomApiRoute from "./routes/room_api.js"
import messageApiRoute from "./routes/message_api.js"
//import and connect mongoose
import mongoose from "mongoose";
await mongoose.connect(MONGO_URI);
//delete all collections -- USE FOR TESTING
// import {dropCollections} from "./utils/drop_collections.js";
// if (TEST){
// await dropCollections()
// }
//http server import
import http from "http";
//import socket.io and create the server
import { Server } from "socket.io";
//chat functions import
import chat from "./chat.js";
import router from "./routes/message_api.js";
let app = express();
const httpServer = http.createServer(app);
const io = new Server(
httpServer,
{
cors:{
origin:"*",
methods:["GET", "POST"]
}
});
//cors middleware
app.options('*', cors()) // include before other routes
app.use(cors())
//json middleware
app.use(express.json());
//form data middleware
app.use(express.urlencoded({ extended: false }));
//static file serving
app.use(express.static("./public"));
//middleware for logging every info about the received request
app.use((req, res, next)=>{
console.warn('----------------HTTP REQUEST---------------------')
console.warn('date: ', new Date())
console.warn('ip:', req.ip)
console.warn('url:', req.url)
console.warn('method: ', req.method)
console.warn('params:', req.params)
console.warn('headers:', req.headers)
console.warn('body:', req.body)
console.warn('-------------------------------------------------')
return next()
})
//redirect to routes
app.use("/api/users", userApiRoute);
app.use("/api/rooms", roomApiRoute);
app.use("/api/messages", messageApiRoute)
//root get request
app.get("/", function (req, res) {
res.sendFile("public/index.html");
});
//SOCKET IO ROUTES--------------
//when a user connects
io.on("connection", function (socket) {
console.log(`socket id: ${socket.id}`)
chat(io, socket);
});
//------------------------------
httpServer.listen(process.env.PORT || PORT, function () {
console.log(`Server running on port ${PORT}`);
});