-
Notifications
You must be signed in to change notification settings - Fork 42
/
server.js
90 lines (74 loc) · 2.62 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
86
87
88
89
90
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const autoIncrement = require('mongoose-auto-increment')
const http = require('http')
const socketServer =require('socket.io')
const app = express();
const todoModel = require('./models/todoModel') //todo model
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())
// MONGOOSE CONNECT
// ===========================================================================
mongoose.connect('mongodb://localhost:27017/local')
var db = mongoose.connection
db.on('error', ()=> {console.log( '---Gethyl FAILED to connect to mongoose')})
db.once('open', () => {
console.log( '+++Gethyl connected to mongoose')
})
var serve = http.createServer(app);
var io = socketServer(serve);
serve.listen(3000,()=> {console.log("+++Gethyl Express Server with Socket Running!!!")})
/***************************************************************************************** */
/* Socket logic starts here */
/***************************************************************************************** */
const connections = [];
io.on('connection', function (socket) {
console.log("Connected to Socket!!"+ socket.id)
connections.push(socket)
socket.on('disconnect', function(){
console.log('Disconnected - '+ socket.id);
});
var cursor = todoModel.find({},"-_id itemId item completed",(err,result)=>{
if (err){
console.log("---Gethyl GET failed!!")
}
else {
socket.emit('initialList',result)
console.log("+++Gethyl GET worked!!")
}
})
// .cursor()
// cursor.on('data',(res)=> {socket.emit('initialList',res)})
socket.on('addItem',(addData)=>{
var todoItem = new todoModel({
itemId:addData.id,
item:addData.item,
completed: addData.completed
})
todoItem.save((err,result)=> {
if (err) {console.log("---Gethyl ADD NEW ITEM failed!! " + err)}
else {
// connections.forEach((currentConnection)=>{
// currentConnection.emit('itemAdded',addData)
// })
io.emit('itemAdded',addData)
console.log({message:"+++Gethyl ADD NEW ITEM worked!!"})
}
})
})
socket.on('markItem',(markedItem)=>{
var condition = {itemId:markedItem.id},
updateValue = {completed:markedItem.completed}
todoModel.update(condition,updateValue,(err,result)=>{
if (err) {console.log("---Gethyl MARK COMPLETE failed!! " + err)}
else {
// connections.forEach((currentConnection)=>{
// currentConnection.emit('itemMarked',markedItem)
// })
io.emit('itemMarked',markedItem)
console.log({message:"+++Gethyl MARK COMPLETE worked!!"})
}
})
})
});