-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
65 lines (51 loc) · 1.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
// Load environmental variables only in dev mode
if (process.env.NODE_ENV !== 'production') {
require('dotenv').load();
}
const express = require('express');
const bodyParser = require('body-parser')
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const mongoose = require('mongoose');
app.use(express.static(__dirname));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
const Message = mongoose.model('Message',{
name : String,
message : String,
date: { type: Date, default: Date.now }
});
const dbUrl = `mongodb+srv://${process.env.DBUSERNAME}:${process.env.DBPASSWORD}@cluster0.4ec6x.mongodb.net/?retryWrites=true&w=majority`;
app.get('/messages', (req, res) => {
Message.find({}, null, {sort: {'_id': 1}}, (err, messages) => {
res.send(messages);
})
});
app.get('/messages/:user', (req, res) => {
const user = req.params.user;
Message.find({name: user}, (err, messages) => {
res.send(messages);
});
});
app.post('/messages', (req, res) => {
const message = new Message(req.body);
message.save((err) => {
if(err) {
res.sendStatus(500);
}
req.body.date = message.date;
io.emit('message', req.body);
res.sendStatus(200);
});
});
io.on('connection', () => {
console.log('A user is connected');
});
mongoose.connect(dbUrl, (err) => {
console.log('mongodb connected', err);
});
const port = process.env.PORT || 3000;
const server = http.listen(port, () => {
console.log('Server is running on port', server.address().port);
});