-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
94 lines (75 loc) · 2.24 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
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const passport = require('passport');
const config = require('./config/database');
let io = require('socket.io');
const http = require('http');
const app = express();
const server = http.createServer(app);
io = io.listen(server);
const users = [];
const connections = [];
//Connect to database
mongoose.connect(config.database);
//On connection
mongoose.connection.on("connected", () => {
console.log("Connected to Database " + config.database);
});
//Database Error
mongoose.connection.on("err", (err) => {
console.log(err);
});
const port = 3000;
const user = require('./routes/users');
//CORS Middleware
app.use(cors());
//Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
//bodyParser Middleware
app.use(bodyParser.json());
//Passport Middleware
app.use(passport.initialize());
app.use(passport.session());
//Calling passport.js with parameter passport to the function
require('./config/passport')(passport);
//for all user routes
app.use('/users', user);
//Index Route
app.get('/', (req, res) => {
res.send("home page")
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'public/index.html'));
});
io.on('connection', function(socket) {
connections.push(socket);
console.log('Connected: ' + connections.length);
// Deleting Disconnected Users
socket.on('disconnect', (data) => {
users.splice(users.indexOf(socket.username), 1);
updateUsername();
connections.splice(connections.indexOf(socket), 1);
});
// Send Message
socket.on('message', function(data){
io.emit('message', {msg: data, user: socket.username});
});
// Adding New User
socket.on('newUser', (data) => {
socket.username = data;
if(users.indexOf(socket.username) == -1) {
users.push(socket.username);
}
updateUsername();
});
function updateUsername() {
io.sockets.emit('getUsers', users);
}
});
//Start Server
server.listen(process.env.PORT || port, () => {
console.log("Server Starting on port " + port +"/"+process.env.PORT);
});