-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathCursor.js
More file actions
114 lines (97 loc) · 2.36 KB
/
Cursor.js
File metadata and controls
114 lines (97 loc) · 2.36 KB
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
//cowboy cursor mock
var util = require('util');
var _q = require('./util');
var ReadableStream = require('stream').Readable;
function map(fields) {
var keys = Object.keys(fields);
var exclude = keys.every(function(key) {
return fields[key] === -1;
});
var include = keys.every(function(key) {
return !!fields[key] && fields[key] !== -1;
});
if(!exclude && !include) {
throw 'you can either select fields to include, or select fields to exclude';
}
return function(doc) {
var mapped = {};
if (exclude) {
keys.forEach(function (key) {
delete doc[key];
});
return doc;
}
keys.forEach(function (key) {
mapped[key] = doc[key];
});
return mapped;
};
}
var Cursor = function (source, query, fields, options) {
this._fields = fields || {};
this._source =_q(source).find(query, options);
this.data = null;
this.index = 0;
ReadableStream.call(this, {objectMode: true});
};
util.inherits(Cursor, ReadableStream);
Cursor.prototype._read = function () {
var self = this;
if (this.index < this._source.length) {
//mock 'reading time'
setTimeout(function () {
self.push(map(self._fields)(self._source[self.index]));
self.index++;
},5);
} else {
self.push(null);
}
};
Cursor.prototype.toArray = function (callback) {
if (this.data===null) {
this.data = this._source.map(map(this._fields));
}
callback(null, this.data);
};
Cursor.prototype.sort = function(sortObj) {
if (this.data===null) {
this.data = this._source.map(map(this._fields));
}
this.data = this.data.sort(function(i1,i2){
for (var d in sortObj) {
if (sortObj.hasOwnProperty(d)) {
if (i1[d]>i2[d]) {
return sortObj[d];
}
if (i1[d]<i2[d]) {
return -1*sortObj[d];
}
}
}
return 0;
});
return this;
};
Cursor.prototype.hasNext = function() {
if (this.data===null) {
this.data = this._source.map(map(this._fields));
}
return this.index<this.data.length;
};
Cursor.prototype.next = function() {
if (this.data===null) {
this.data = this._source.map(map(this._fields));
}
var dat = this.data[this.index];
this.index++;
return dat;
};
Cursor.prototype.batchSize = function() {
return this;
};
Cursor.prototype.addCursorFlag = function() {
return this;
};
Cursor.prototype.close = function() {
};
module.exports = Cursor;