/
collection.js
262 lines (224 loc) · 6.35 KB
/
collection.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
'use strict';
var _ = require('lodash');
var Bluebird = require('bluebird');
var Backbone = require('backbone');
var Model = require('./model');
var debug = require('./debug');
// Cache ensured indexes
var INDEXED = {};
module.exports = Backbone.Collection.extend({
/**
* Takes the mongodb response and calls the Backbone success method
*
* @param {Object} options
* @return {Function}
*/
_wrapResponse: function(options) {
return function(err, resp) {
if (err) {
options.error(err);
} else {
options.success(resp[0]);
}
};
},
model: Model,
initialize: function() {
this.db; // reference to a mongodb client/connection
},
/**
* Copied from Backbone, not currently overridden
*/
parse: function(resp, options) {
return resp;
},
/**
* Override to assign `db` and `user` to all models in the collection on `set`
* Note that the prototype must be called first and returned at the end
*/
set: function() {
var ret = Backbone.Collection.prototype.set.apply(this, arguments);
this.each(function(model) {
// Assign `db` to all models in the collection
if (this.db) {
model.db = this.db;
}
// Assign `user` to all models in the collection
if (this.user) {
model.user = this.user;
}
}.bind(this));
return ret;
},
/**
* Creates an array of pojos
* By calling `Model.render` on all models in collection
*
* @param {Object} options
* @return {Array}
*/
render: function(options) {
return this.map(function(model) {
return model.render(options);
});
},
/**
* Alias for `render`
*/
toResponse: function() {
return this.render();
},
/**
* Override the backbone sync method for use with mongodb
*
* The `options` object can contains 2 callbacks:
* Both callbacks have parameters (model, resp, options)
* `resp` is either a `document` or an `error` object
*
* - `success`
* - `error`
*
* Events:
*
* - A `request` event is fired before with parameters (model, op, options)
* - A `sync` event is fired after with parameters (model, resp, options)
*
* @param {String} method
* @param {Model} model
* @param {Object} options
* @return {Promise.<Collection>}
*/
sync: Bluebird.method(function(method, model, options) {
var op = this[method].call(this, model, options);
model.trigger('request', model, op, options);
return op;
}),
/**
* Override the backbone read method for use with mongodb
*
* The parameter `options` has the following properties:
*
* - `limit` Limit number of documents returned in query
* - `skip` Skip N documents ahead in query
* - `sort` Set to sort the documents coming back from the query `[['a', 1]]`
* - `fields` Restrict the fields to return in the query `{'a': 1}`
* - `readPreference` Use a read preference when running this query
*
* @param {Collection} collection
* @param {Object} options
* @return {Promise.<Collection>}
*/
read: Bluebird.method(function(collection, options) {
options = options || {};
var query = {};
// Build query against where query
if (_.isObject(options.query)) {
query = options.query;
}
// Restrict mongo options
var mongoOptions = _.pick(options, [
'limit',
'skip',
'sort',
'fields',
'readPreference'
]) || {};
debug.info('Collection [%s] read with query: %s and options: %s',
this.model.prototype.urlRoot,
JSON.stringify(query),
JSON.stringify(mongoOptions));
return Bluebird.bind(this).tap(function() {
return this.ensureIndexes();
}).then(function() {
return this.db.find(
this.model.prototype.urlRoot,
query,
mongoOptions,
this._wrapResponse(options)
);
}).tap(function(resp) {
// Assign pagination properties to the collection
this.limit = _.parseInt(mongoOptions.limit) || 0;
this.skip = _.parseInt(mongoOptions.skip) || 0;
this.total = _.parseInt(resp[1]) || 0;
this.count = this.length;
this.page = Math.ceil((this.skip / this.limit) || 0) + 1;
this.pages = _.isFinite(Math.ceil(this.total / this.limit)) ?
Math.ceil(this.total / this.limit) :
1;
this.hasMore = this.page < this.pages;
}).return(this);
}),
/**
* A new method for counting with mongodb
* This is an extension to backbone
*
* * The parameter `options` has the following properties:
*
* - `limit` Limit number of documents returned in query
* - `skip` Skip N documents ahead in query
* - `readPreference` Use a read preference when running this query
*
* @param {Object} options
* @return {Promise.<Number>} Number of documents matching query
*/
count: Bluebird.method(function(options) {
options = options || {};
// This is for `_wrapResponse`
// `options` may contain `success` and `error` callbacks
var successCallback = options.success;
var errorCallback = options.error;
options.success = function(resp) {
if (successCallback) {
successCallback(resp);
}
};
options.error = function(err) {
if (errorCallback) {
errorCallback(err);
}
};
// Build query against where query
var query = {};
if (_.isObject(options.query)) {
query = options.query;
}
// Restrict mongo options
var mongoOptions = _.pick(options, [
'limit',
'skip',
'readPreference'
]) || {};
debug.info('Collection [%s] count with query: %s and options: %s',
this.model.prototype.urlRoot,
JSON.stringify(query),
JSON.stringify(mongoOptions));
return Bluebird.bind(this).tap(function() {
return this.ensureIndexes();
}).then(function() {
return this.db.count(
this.model.prototype.urlRoot,
query,
mongoOptions,
this._wrapResponse(options)
);
});
}),
/**
* Ensure model indexes are created if defined
* Only once per process/collection
*
* @return {Promise}
*/
ensureIndexes: Bluebird.method(function() {
var collection = this.model.prototype.urlRoot;
if (INDEXED[collection]) {
// No-op
return;
}
INDEXED[collection] = true;
var model = new this.model();
model.db = this.db;
return model.ensureIndexes();
})
});