-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
90 lines (64 loc) · 2.05 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
const express = require('express');
const session = require('express-session')
const bp = require('body-parser');
const http = require('http');
const morgan = require('morgan');
const cors = require('cors');
// ENVIRONMENT SETUP
require('dotenv').config();
if(require('dotenv').config().error){consol.log("Environment Varaible Error Occured")}
const { addUser, getUsersInRoom, getUser, removeUser } = require('./opperations/chat/chat');
const PORT = process.env.PORT || 5000;
const app = express();
const server = http.createServer(app);
//BODY PARSER
app.use(bp.json());
//BODY PARSER
app.use(bp.urlencoded({extended: true}));
// MORGAN DEV TOOLS
app.use(morgan('dev'));
// SESSION / TOKEN
app.set('trust proxy', 1) // trust first proxy
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}))
app.use(cors());
app.options('*', cors());
// ROUTING
require('./router')(app);
// const router = require('./router');
// app.use(router);
// SOCKET.IO
const io = require("socket.io")(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"]
}
});
io.on("connection", (socket)=>{
socket.on("join", ({username, room}, callback)=>{
// Initiation
const {user, error} = addUser({id:socket.id, username, room});
// const error = "";
// Error Handling
if(error){
return callback(error);
}
socket.emit("message", {user: "system", text: `${user.username}, Welcome to the SafeTech ${user.room}`});
socket.broadcast.to(user.room).emit("message", {user: "system", text: `${username} has joined`});
socket.join(user.room);
callback();
});
socket.on("sendMessage", (messeage, callback) => {
const user = getUser(socket.id);
io.to(user.room).emit("message", {user: user.username, text: messeage });
callback();
})
socket.on("endit", ()=>{
console.log("User left!");
});
});
server.listen(PORT, () => {console.log("Server is running on "+ PORT)});