-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
70 lines (63 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
const express = require('express');
let bodyParser = require('body-parser')
const path = require('path');
const app = express();
let http = require('http').Server(app)
let io = require('socket.io')(http)
const port = process.env.PORT || 5000;
let mongoose = require('mongoose')
const dbUrl = 'mongodb://user:[email protected]:35243/learning-node'
let Message = mongoose.model('Message',{
name: String,
message: String
})
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:false}))
app.get('/messages', (req, res)=>{
Message.find({},(err, messages)=>{
res.send(messages)
})
})
app.get('/messages/:user', (req, res)=>{
let user = req.params.user
Message.find({name: user},(err, messages)=>{
res.send(messages)
})
})
app.post('/messages', async (req, res)=>{
try {
// throw "some error" //for testing purpose
let message = new Message(req.body)
let messageSaved = await message.save()
console.log('Message saved!', messageSaved)
let censored = await Message.findOne({message: 'badword'})
if(censored){
console.log('Censored words found', censored)
await Message.deleteOne({_id: censored.id})
console.log('Censored word deleted!')
} 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')
})
if (process.env.NODE_ENV === 'production') {
// Serve any static files
app.use(express.static(path.join(__dirname, 'client/build')));
// Handle React routing, return all requests to React app
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});
}
mongoose.connect(dbUrl,{useNewUrlParser: true},(err)=>{
console.log('mongo db connection', err)
})
http.listen(port, () => console.log(`Listening on port ${port}`));