-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
88 lines (75 loc) · 2.28 KB
/
db.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
var mongoose = require('mongoose');
var Schema = require('mongoose');
const Message = new Schema({
message: String,
date: { type: Date, default: Date.now },
uid: String,
});
class MessageCache {
constructor() {
this.messages = [];
this.idMap = [];
this.tail = '';
this.pending = true; // to do initial loading
this.timeoutId = undefined;
}
notifyWorker() {
this.pending = true;
}
startWorker() {
const loadData = () => {
return Message.find()
.sort({_id: -1})
.limit(25)
.exec()
.then(
(messages) => {
if(messages.length == 0) {
return false;
}
messages.reverse();
this.messages = messages;
this.idMap = messages.map(
(msg) => {
return msg._id.toString();
}
);
this.tail = this.idMap[messages.length-1];
return true;
}
).catch(
(error) => {
console.error(error.stack);
return false;
}
);
};
const work = () => {
if(this.pending) {
console.log("Data Loading..");
this.pending = false;
loadData().then(
(success) => {
if(!success) {
this.pending = true;
this.timeoutId = setTimeout(work, 3000);
return;
}
console.log('Cache is updated - ', this.messages[0]._id);
this.timeoutId = setTimeout(work, 5);
}
);
return;
}
this.timeoutId = setTimeout(work, 5);
};
work();
}
getRecentMsg(id) {
const index = this.idMap.indexOf(id);
if(this.idMap.indexOf(id) == -1)
return undefined;
return this.messages.slice(index+1, this.messages.length);
}
}
export default MessageCache;