-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.js
240 lines (211 loc) · 6.55 KB
/
server.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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
// Retrieve confidential information from .env file
const result = require('dotenv').config();
if (result.error) {
throw result.error;
}
// import statements
const express = require('express');
const mongoose = require('mongoose');
const { queryParser } = require('express-query-parser');
const helmet = require('helmet');
const compression = require('compression');
const Message = require('./models/Message');
const User = require('./models/User');
const isEmpty = require('lodash/isEmpty');
// Initialize app to a server
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server, {
cors: {
origin: ['http://localhost:3000', 'http://localhost:64226'],
methods: ['GET', 'POST'],
allowedHeaders: ['my-custom-header'],
credentials: true,
},
});
const cors = require('cors');
var corsOptions = {
// Specifies the origin(s) from which a server request can occur aside from its own origin
origin: ['http://localhost:3000', 'http://localhost:64226'],
};
app.use(cors(corsOptions));
// Increase security by configuring headers
app.use(helmet());
// Compresses the request from client
app.use(compression());
// Allows parsing of JSON from client
app.use(express.json());
// Allows parsing of x-www-form-urlencoded
app.use(
express.urlencoded({
extended: false,
})
);
// Converts booleans in url parameter into actual booleans instead of treating them like string, similarly for null
app.use(
queryParser({
parseNull: true,
parseBoolean: true,
})
);
// Gets the URI of the MongoDB database used by app
const db = require('./config/keys').mongoURI; // Can change to mongoAtlasURI to connect to cloud database
// mongoDB settings
const options = {
useNewUrlParser: true,
useCreateIndex: true,
// autoIndex: true, // Will result in rejection of duplicate entries
keepAlive: true,
poolSize: 10,
bufferMaxEntries: 0,
connectTimeoutMS: 10000,
socketTimeoutMS: 45000,
family: 4, // Use IPv4, skip trying IPv6
useFindAndModify: false,
useUnifiedTopology: true,
};
// Socket.io connections between client and server
io.on('connection', (socket) => {
User.find({})
.sort({ _id: 1 })
.then((users) => {
// console.log(users);
socket.emit('outputUser', users);
socket.emit('onlineUsers', users.length);
Message.find({})
.limit(100)
.sort({ _id: 1 })
.then((messages) => {
socket.emit('outputMessage', messages);
})
.catch((err) => console.log(err));
})
.catch((err) => console.log(err));
const setStatus = (msg) => {
socket.emit('status', msg);
};
socket.on('inputUser', (data) => {
const newUser = new User({
_id: socket.id,
username: data.username,
avatar: data.avatar,
lat: data.lat,
lng: data.lng,
});
newUser
.save()
.then((user) => {
io.emit('outputUser', [user]);
User.find({}).then((users) => {
io.emit('onlineUsers', users.length);
});
})
.catch((err) => console.log(err));
});
socket.on('inputMessage', (data) => {
if (isEmpty(data.text)) {
setStatus('Please enter text');
} else {
User.findOne({ _id: socket.id })
.then((user) => {
if (user) {
const newMessage = new Message({
_id: Math.floor(Date.now() / 1000) + '-' + socket.id,
username: user.username,
userId: socket.id,
text: data.text,
});
console.log('going to emit');
newMessage
.save()
.then((message) => {
console.log('emitting');
io.emit('outputMessage', [message]);
})
.catch((err) => {
console.log(err);
});
}
})
.catch((err) => console.log(err));
}
});
socket.on('inputPosition', (data) => {
if (!data.lng || !data.lat) {
setStatus('No lng or lat included', data);
} else {
User.findOne({ _id: socket.id })
.then((userToUpdate) => {
if (!userToUpdate) {
console.log(`User with ID ${socket.id} does not exist in database`);
} else {
userToUpdate.lng = data.lng;
userToUpdate.lat = data.lat;
userToUpdate
.save()
.then((updatedUser) => {
io.emit('outputPosition', [updatedUser]);
})
.catch((err) => console.log(err));
}
})
.catch((err) => console.log(err));
}
});
socket.on('inputUpdateUser', (updatedData) => {
User.findOne({ _id: socket.id })
.then((userToUpdate) => {
if (userToUpdate) {
userToUpdate.username = isEmpty(updatedData.username)
? userToUpdate.username
: updatedData.username;
userToUpdate.avatar = isEmpty(updatedData.avatar)
? userToUpdate.avatar
: updatedData.avatar;
userToUpdate.lat = isEmpty(updatedData.lat) ? userToUpdate.lat : updatedData.lat;
userToUpdate.lng = isEmpty(updatedData.lng) ? userToUpdate.lng : updatedData.lng;
userToUpdate
.save()
.then((updatedUser) => {
io.emit('outputUpdateUser', [updatedUser]);
})
.catch((err) => console.log(err));
}
})
.catch((err) => console.log(err));
});
socket.on('disconnect', () => {
User.findOneAndRemove({ _id: socket.id })
.then((user) => {
if (user) {
console.log('emitting disconnect for user ' + user.username);
socket.broadcast.emit('userLeft', socket.id);
User.count({}, (err, count) => {
socket.broadcast.emit('onlineUsers', count);
});
}
})
.catch((err) => console.log(err));
});
});
// Connect to the specified MongoDB database
mongoose
.connect(db, options)
.then(() => {
console.log('MongoDB successfully connected');
})
.catch((err) => console.log(err));
// Uses process.env.PORT if available otherwise 5000
const port = process.env.PORT || 5000;
const cleanDatabase = async () => {
await mongoose.connection.db.dropDatabase();
server.close();
};
// listen for TERM signal .e.g. kill
process.on('SIGTERM', () => cleanDatabase());
// listen for INT signal e.g. Ctrl-C
process.on('SIGINT', () => cleanDatabase());
// or even exit event
process.on('exit', () => cleanDatabase());
// Tells the server which port to listen on
server.listen(port, () => console.log(`Server up and running on port ${port}!`));