-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
76 lines (57 loc) · 1.67 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
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
app.use(express.static(__dirname));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
io.on('connection', () => {
console.log('a user is connected');
});
// mongodb atlas connection and server creation
const dbUrl = 'mongodb+srv://bhargav:[email protected]/?retryWrites=true&w=majority';
let server;
mongoose.connect(dbUrl, (err) => {
if (err) {
console.log("unable to connect to db :(");
console.log("Exiting...");
console.log("err:", err);
}
else {
console.log("db connection established...");
// create server and listen on port
server = http.listen(3000, (err) => {
if (err) console.log("unable to listen on port...") && console.log("err: ", err);
else console.log("server is running on port", server.address().port);
});
}
});
// defining schema and compiling model
const Message = mongoose.model('Message', {
name: String,
text: String
});
// ROUTES
app.get('/messages', (req, res) => {
Message.find({}, (err, messages) => {
if (err)
res.sendStatus(500);
else
res.send(messages);
});
});
app.post('/messages', (req, res) => {
if (req.body.name.trim() == "" || req.body.text.trim() == "")
res.sendStatus(500);
let message = new Message(req.body);
message.save(err => {
if (!err) {
io.emit('message', req.body);
res.sendStatus(200);
}
else
res.sendStatus(500);
});
});