-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
84 lines (62 loc) · 1.98 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
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// it needs to tie in with express
// we'll create a regular HTTP server with Node that will share with Express and Socket.IO
const http = require('http').Server(app);
const io = require('socket.io')(http);
const mongoose = require('mongoose');
const { dbURL } = require('./config');
var Message = mongoose.model('Message', {
name: String,
message: String
})
app.use(express.static(__dirname));
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
mongoose.Promise = Promise;
mongoose.connect(dbURL, { useNewUrlParser: true, useUnifiedTopology: true }, err => {
console.log('mongodb connected', err)
})
const messages = [
{ name: 'Tim', message: 'hi!'},
{ name: 'Jack', message: 'hello'},
]
app.get('/messages', (req, res) => {
Message.find({}, (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', async (req, res) => {
try {
var message = new Message(req.body);
await message.save();
console.log('saved')
var censored = await Message.findOne({ message: 'badword' });
if (censored) {
console.log('censored word found', censored);
await Message.deleteOne({ _id: censored.id})
} else {
io.emit('message', req.body)
}
res.sendStatus(200);
} catch (error) {
res.sendStatus(500);
return console.error(error)
} finally {
console.log('message post called');
}
});
io.on('connection', socket => {
console.log('a user connected')
})
// use http server instead of express
const server = http.listen(3000, () => {
console.log('server is listening on port', server.address().port);
})