-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
76 lines (64 loc) · 2.17 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 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 dbUrl = "mongodb+srv://proj-0-admin-0:[email protected]/messagesDB?retryWrites=true&w=majority";
var Message =mongoose.model('Message',{
name:String,
message:String
})
app.post('/messages', (req,res) =>{
var message = new Message(req.body);
message.save().then(() =>{
console.log('Saved to the database')
Message.findOne(({message: "badword"}, (err, unkwon) =>{
if(unkwon){
console.log('censored words found', unkwon);
Message.deleteOne({_id: unkwon.id}, (err) =>{
console.log('removed censored message',err);
})
}
else{
console.log(err);
}
})).catch((err) =>{
res.sendStatus(500);
return console.log('database error', err)
});
console.log(req.body);
io.emit('message', req.body)
res.sendStatus(200);
});
});
app.get('/messages', (req,res) =>{
Message.find({},{name: 1, message:1, _id: 0 }, (err,messages) =>{
if(err){
sendStatus(500);
}
let messageObject = messages.toString()
res.send(JSON.stringify(messageObject)+'\n');
});
});
app.get('/messages/:user', (req,res) =>{
var user = req.params.user
Message.find({name: user},{name: 1, message:1, _id: 0 }, (err,messages) =>{
if(err){
sendStatus(500);
}
res.send(messages)
});
});
io.on('connection', (socket) =>{
console.log('user connected');
});
mongoose.connect(dbUrl, {useMongoClient:true},{useNewUrlParser:true},{useUnifiedTopology: true},(err) =>{
console.log('mongoDB connection', err);
})
let server = http.listen(4000, () =>{
console.log('server is running on port', server.address().port);
});