-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
85 lines (63 loc) · 2.04 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
85
require('dotenv').config();
const Message = require('./models/message.schema')
var express = require('express'),
path = require("path"),
app = express(),
server = app.listen(3801),
socket = require('socket.io'),
DIST_DIR = path.join(__dirname, "dist"),
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
io = socket(server);
/** MIDDLEWARES **/
mongoose.Promise = global.Promise;
//get content of incoming request under req.body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
//allow CORS
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
//serve site
//app.use(express.static(DIST_DIR));
//routes
app.use(require('./routes'));
/****************/
console.log(process.env)
mongoose.connect("mongodb://127.0.0.1:27017/test",{useNewUrlParser:true}).then(function(response){
console.log('i am in !');
}).catch(error=>{
console.log(error);
});
mongoose.set('useCreateIndex', true);
mongoose.connection.once('open',function(){
console.log('connected');
}).on('error',function(error){
console.log(error);
});
io.sockets.on('connection', function(socket){
console.log('socket : new connection');
console.log(socket.id);
socket.emit('newUser',socket.id);
socket.on('sendMessage',function(data){
var newMessage = new Message(data);
newMessage.save().then(function(response){
console.log('save res')
console.log(response)
io.emit('readMsg',response)
//res.send({savedMessage : response});
}).catch(function(err){
console.log(err)
});
});
socket.on('disconnect', disconnect);
});
function disconnect(socket){
console.log(socket)
console.log(socket.id + ' disconnect');
}
function newConnection(socket) {
console.log('new one so its still on')
}