-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathclient.js
268 lines (222 loc) · 6.61 KB
/
client.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
SearchSource = function SearchSource(source, fields, options) {
this.source = source;
this.searchFields = fields;
this.currentQuery = null;
this.options = options || {};
this.status = new ReactiveVar({loaded: true});
this.metaData = new ReactiveVar({});
this.history = {};
this.store = new Mongo.Collection(null);
this._storeDep = new Tracker.Dependency();
this._currentQueryDep = new Tracker.Dependency();
this._currentVersion = 0;
this._loadedVersion = 0;
}
SearchSource.prototype._loadData = function(query, options) {
var self = this;
var version = 0;
var historyKey = query + EJSON.stringify(options);
if(this._canUseHistory(historyKey)) {
this._updateStore(this.history[historyKey].data);
this.metaData.set(this.history[historyKey].metadata);
self._storeDep.changed();
} else {
this.status.set({loading: true});
version = ++this._currentVersion;
this._fetch(this.source, query, options, handleData);
}
function handleData(err, payload) {
if(err) {
self.status.set({error: err});
throw err;
} else {
if(payload instanceof Array) {
var data = payload;
var metadata = {};
} else {
var data = payload.data;
var metadata = payload.metadata;
self.metaData.set(payload.metadata || {});
}
if(self.options.keepHistory) {
self.history[historyKey] = {data: data, loaded: new Date(), metadata: metadata};
}
if(version > self._loadedVersion) {
self._updateStore(data);
self._loadedVersion = version;
}
if(version == self._currentVersion) {
self.status.set({loaded: true});
}
self._storeDep.changed();
}
}
};
SearchSource.prototype._canUseHistory = function(historyKey) {
var historyItem = this.history[historyKey];
if(this.options.keepHistory && historyItem) {
var diff = Date.now() - historyItem.loaded.getTime();
return diff < this.options.keepHistory;
}
return false;
};
SearchSource.prototype._updateStore = function(data) {
var self = this;
var storeIds = _.pluck(this.store.find().fetch(), "_id");
var currentIds = [];
data.forEach(function(item) {
currentIds.push(item._id);
self.store.update(item._id, item, {upsert: true});
});
// Remove items in client DB that we no longer need
var currentIdMappings = {};
_.each(currentIds, function(currentId) {
// to support Object Ids
var str = (currentId._str)? currentId._str : currentId;
currentIdMappings[str] = true;
});
_.each(storeIds, function(storeId) {
// to support Object Ids
var str = (storeId._str)? storeId._str : storeId;
if(!currentIdMappings[str]) {
self.store.remove(storeId);
}
});
};
SearchSource.prototype.search = function(query, options) {
this.currentQuery = query;
this._currentQueryDep.changed();
this._loadData(query, options);
if(this.options.localSearch) {
this._storeDep.changed();
}
};
SearchSource.prototype.getData = function(options, getCursor) {
options = options || {};
var self = this;
this._storeDep.depend();
var selector = {$or: []};
var regExp = this._buildRegExp(self.currentQuery);
// only do client side searching if we are on the loading state
// once loaded, we need to send all of them
if(this.getStatus().loading) {
self.searchFields.forEach(function(field) {
var singleQuery = {};
singleQuery[field] = regExp;
selector['$or'].push(singleQuery);
});
} else {
selector = {};
}
function transform(doc) {
if(options.transform) {
self.searchFields.forEach(function(field) {
if(self.currentQuery && doc[field]) {
doc[field] = options.transform(doc[field], regExp, field, self.currentQuery);
}
});
}
if(options.docTransform) {
return options.docTransform(doc);
}
return doc;
}
var cursor = this.store.find(selector, {
sort: options.sort,
limit: options.limit,
transform: transform
});
var collection = this.options.collection;
if(collection) {
var ids = _.pluck(cursor.fetch(), '_id');
if (!this.options.subscriptionName) {
throw Error('subscritionName is missing');
}
var sub = Meteor.subscribe(this.options.subscriptionName, ids);
if (!sub.ready())
return [];
var docs = collection.find({
_id: {
$in: ids
}
}, {
transform: transform
}).fetch();
var sortIds = _.invert(_.object(_.pairs(ids)));
var sorted = _.sortBy(docs, function(x) {
return sortIds[x._id];
});
return sorted;
}
if(getCursor) {
return cursor;
}
return cursor.fetch();
};
SearchSource.prototype._fetch = function(source, query, options, callback) {
if(typeof this.fetchData == 'function') {
this.fetchData(query, options, callback);
} else if(Meteor.status().connected) {
this._fetchDDP.apply(this, arguments);
} else {
this._fetchHttp.apply(this, arguments);
}
};
SearchSource.prototype._fetchDDP = function(source, query, options, callback) {
Meteor.call("search.source", this.source, query, options, callback);
};
SearchSource.prototype._fetchHttp = function(source, query, options, callback) {
var payload = {
source: source,
query: query,
options: options
};
var headers = {
"Content-Type": "text/ejson"
};
HTTP.post('/_search-source', {
content: EJSON.stringify(payload),
headers: headers
}, function(err, res) {
if(err) {
callback(err);
} else {
var response = EJSON.parse(res.content);
if(response.error) {
callback(response.error);
} else {
callback(null, response.data);
}
}
});
};
SearchSource.prototype.getMetadata = function() {
return this.metaData.get();
};
SearchSource.prototype.getCurrentQuery = function() {
this._currentQueryDep.depend();
return this.currentQuery;
}
SearchSource.prototype.getStatus = function() {
return this.status.get();
};
SearchSource.prototype.cleanHistory = function() {
this.history = {};
};
SearchSource.prototype._buildRegExp = function(query) {
query = query || "";
var afterFilteredRegExpChars = query.replace(this._getRegExpFilterRegExp(), "\\$&");
var parts = afterFilteredRegExpChars.trim().split(' ');
return new RegExp("(" + parts.join('|') + ")", "ig");
};
SearchSource.prototype._getRegExpFilterRegExp = _.once(function() {
var regExpChars = [
"\\", "^", "$", "*", "+", "?", ".",
"(", ")", ":", "|", "{", "}", "[", "]",
"=", "!", ","
];
var regExpCharsReplace = _.map(regExpChars, function(c) {
return "\\" + c;
}).join("|");
return new RegExp("(" + regExpCharsReplace + ")", "g");
});