This repository has been archived by the owner on Jan 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCursor.js
140 lines (127 loc) · 3.64 KB
/
Cursor.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
var AbstractCursor = require('springbokjs-db/lib/AbstractCursor').AbstractCursor;
export class Cursor extends AbstractCursor {
constructor(cursor, store, query) {
this._cursor = cursor;
this._store = store;
this._query = query;
}
get query() {
return this._query;
}
advance(count) {
this._cursor.skip(count);
return this;
}
next() {
return new Promise((resolve, reject) => {
this._cursor.nextObject((err, value) => {
if (err) {
return reject(err);
}
this._result = value;
this.key = value && value._id;
resolve(this.key);
});
});
}
limit(newLimit) {
return new Promise((resolve, reject) => {
this._cursor.limit(newLimit, (err) => {
if (err) {
return reject(err);
}
resolve();
});
});
}
count(applyLimit) {
return new Promise((resolve, reject) => {
this._cursor.count(applyLimit, (err, result) => {
if (err) {
return reject(err);
}
resolve(result);
});
});
}
result() {
return Promise.resolve(this._result);
}
remove() {
return this._store.deleteByKey(this.key);
}
forEach(callback) {
return this.forEachResults((result) => {
return callback(this._store.toVO(result));
});
}
forEachResults(callback) {
return new Promise((resolve, reject) => {
var waitFor = 0;
this._cursor.each((err, result) => {
if (err) {
return reject(err);
}
if (result === null) {
// end !
this.close();
if (waitFor === 0) {
resolve();
}
return;
}
try {
var result = callback(result);
if (result && typeof result.then === 'function') {
waitFor++;
result.then(() => {
if (--waitFor === 0) {
resolve();
}
}).catch(reject);
}
} catch (err) {
console.log(err.stack || err.message);
reject(err);
}
});
});
}
toArray() {
return new Promise((resolve, reject) => {
this._cursor.toArray((err, results) => {
if (err) {
return reject(err);
}
try {
resolve(results.map((v => this._store.toVO(v))));
} catch(err) {
reject(err);
}
});
});
}
close() {
if (this._cursor) {
this._cursor.close();
this._cursor = this._store = this._result = undefined;
}
return Promise.resolve();
}
}
Cursor.prototype[Symbol.iterator] = function() {
return {
next: () => {
return {
done: this._cursor === undefined,
value: this.next().then((key) => {
if (key === null) {
this.close();
return undefined;
}
return this.vo();
})
};
}
};
};