-
Notifications
You must be signed in to change notification settings - Fork 0
/
question.js
121 lines (90 loc) · 2.54 KB
/
question.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
'use strict';
var r = require('./dash'),
_ = require('lodash');
function setup (io) {
io.on('connection', function(socket){
// r.table('question').indexCreate('createdAt').run(function (err) {
// console.log(err);
// });
socket.on('question:findById', function(id, cb){
r.table('question')
.get(id)
.run(cb);
});
socket.on('question:add', function(record, cb){
record = _.pick(record, 'name', 'question', 'color');
record.createdAt = new Date();
r.table('question')
.insert(record)
.run(function(err, result){
if(err){
cb(err);
}
else{
record.id = result.generated_keys[0];
cb(null, record);
}
});
});
socket.on('question:update', function(record, cb){
record = _.pick(record, 'id', 'name', 'question');
r.table('question')
.get(record.id)
.update(record)
.run(function(err, result){
console.log(err);
if (err) {
cb(err);
} else {
cb(null, result);
}
});
});
socket.on('question:delete', function(id, cb){
r.table('question')
.get(id)
.delete()
.run(cb);
});
socket.on('question:changes:start', function(data){
var limit, filter;
limit = data.limit || 100;
filter = data.filter || {};
r.table('question')
.orderBy({index: r.desc('createdAt')})
.filter(filter)
.limit(limit)
.changes()
.run({cursor: true}, handleChange);
function handleChange(err, cursor){
if(err){
console.log(err);
}
else{
if(cursor){
cursor.each(function(err, record){
if(err){
console.log(err);
}
else{
socket.emit('question:changes', record);
}
});
}
}
socket.on('question:changes:stop', stopCursor);
socket.on('disconnect', stopCursor);
function stopCursor () {
if(cursor){
cursor.close();
}
socket.removeListener('question:changes:stop', stopCursor);
socket.removeListener('disconnect', stopCursor);
}
}
});
});
}
module.exports = {
setup: setup
};