-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.js
48 lines (37 loc) · 899 Bytes
/
index.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
const ROW_NUMBER = Symbol('ROW_NUMBER');
const Watcher = require('./watcher');
class LiveQuery extends Watcher {
// Adds a 'rows' event to the 'watch' handler
query(sql) {
const handler = this.watch(sql);
const state = {};
handler.on('changes', (changes, cols) => {
changes.forEach((change) => {
if(change.data) {
const row = {};
// Set the row number symbol
row[ROW_NUMBER] = change.rn;
change.data.forEach((el, i) => {
row[cols[i]] = el;
});
// Update the state
state[change.id] = Object.freeze(row);
}
else {
// Update the state
delete state[change.id];
}
});
const rows = [];
for(const i in state) {
rows.push(state[i]);
}
rows.sort((a, b) => {
return a[ROW_NUMBER] - b[ROW_NUMBER];
});
handler.emit('rows', rows);
});
return handler;
}
}
module.exports = LiveQuery;