-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdb.js
523 lines (465 loc) · 11.6 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
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
var db = module.exports = {}
, util = require('util')
, EventEmitter = require('events').EventEmitter
, mongodb = require('mongodb')
, uuid = require('./util/uuid')
, scrub = require('scrubber').scrub
, debug = require('debug')('db');
/**
* Create a new database with the given options. You can start making
* database calls right away. They are internally buffered and executed once the
* connection is resolved.
*
* Options:
*
* - `name` the database name
* - `host` the database host
* - `port` the database port
*
* Example:
*
* db
* .create({host: 'localhost', port: 27015, name: 'test'})
* .createStore('testing-store')
* .insert({foo: 'bar'}, fn)
*
* @param {Object} options
* @return {Db}
*/
db.create = function (options) {
var db = new Db(options);
return db;
};
/**
* A `Db` abstracts a driver implementation of the database. This allows for
* a single interface to be used against any database implementation.
*
* Example:
*
* var redis = require('redis');
*
* function Redis(options) {
* this.options = options;
* this._redis = redis.createClient()
* }
* util.inherits(Redis, Db);
*
* Redis.prototype.open = function (fn) {
* this._redis.once('ready', fn);
* }
*
* @param {Object} options
* @api private
*/
function Db(options) {
this.options = options;
debug("options : ", options);
this._mdb = new mongodb.Db(this.options.name, new mongodb.Server(this.options.host, this.options.port));
}
util.inherits(Db, EventEmitter);
db.Db = Db;
/**
* Drop the underlying database.
*
* @param {Function} callback
* @api private
*/
Db.prototype.drop = function (fn) {
getConnection(this, function (err, mdb) {
mdb.open(function () {
mdb.dropDatabase(fn);
});
});
};
/**
* Create a new database store (eg. a collection).
*
* Example:
*
* db
* .connect({host: 'localhost', port: 27015, name: 'test'})
* .createStore('testing-store')
* .insert({foo: 'bar'}, fn)
*
* @param {String} namespace
* @return {Store}
*/
Db.prototype.createStore = function (namespace) {
return new Store(namespace, this);
};
/**
* Initialize a space in the database (eg. a collection).
*
* @param {String} namespace
* @param {Db} db
* @api private
*/
function Store(namespace, db) {
this.namespace = namespace;
this._db = db;
}
module.exports.Store = Store;
function getConnection(db, fn) {
if(db.connected) {
fn(null, db._mdb);
} else if(db.connecting) {
db.once('connection attempted', function (err) {
fn(err, db._mdb);
});
} else {
db.connecting = true;
db._mdb.open(function (err) {
db.connecting = false;
db.emit('connection attempted', err);
if(err) {
db.connected = false;
throw err;
} else {
// check for credentials
var credentials = db.options.credentials;
if (credentials && credentials.username && credentials.password) {
db._mdb.authenticate(credentials.username, credentials.password, function (err) {
if (err) {
db.connected = false;
throw err;
}
db.connected = true;
fn(null, db._mdb);
});
} else {
db.connected = true;
fn(null, db._mdb);
}
}
});
}
}
function collection(store, fn) {
var db = store._db;
getConnection(db, function (err, mdb) {
if(err) return fn(err);
mdb.collection(store.namespace, function (err, collection) {
if(err || !collection) {
console.error(err || new Error('Unable to get ' + store.namespace + ' collection'));
process.exit(1);
}
fn(null, collection);
});
});
}
/**
* Change public IDs to private IDs.
*
* IDs are generated with a psuedo random number generator.
* 24 hexidecimal chars, ~2 trillion combinations.
*
* @param {Object} object
* @return {Object}
* @api private
*/
Store.prototype.identify = function (object) {
if(!object) return;
if(typeof object != 'object') throw new Error('identify requires an object');
var store = this;
function set(object) {
if(object._id) {
object.id = object._id;
delete object._id;
} else {
var u = object.id || store.createUniqueIdentifier();
object._id = u;
delete object.id;
}
}
if(Array.isArray(object)) {
object.forEach(set);
} else {
set(object);
}
return object;
};
/**
* Change query IDs to private IDs.
*
* @param {Object} object
* @return {Object}
* @api private
*/
Store.prototype.scrubQuery = function (query) {
// private mongo ids can be anywhere in a query object
// walk the object recursively replacing id with _id
// NOTE: if you are implementing your own Store,
// you probably wont need to do this if you want to store ids
// as 'id'
if(query.id && typeof query.id === 'object') {
query._id = query.id;
delete query.id;
}
try {
scrub(query, function (obj, key, parent, type) {
// find any value using _id
if(key === 'id' && parent.id) {
parent._id = parent.id;
delete parent.id;
}
});
} catch(ex) {
debug(ex);
}
};
/**
* Create a unique identifier. Override this in derrived stores
* to change the way IDs are generated.
*
* @return {String}
*/
Store.prototype.createUniqueIdentifier = function() {
return uuid.create();
};
/**
* Insert an object into the store.
*
* Example:
*
* db
* .connect({host: 'localhost', port: 27015, name: 'test'})
* .createStore('testing-store')
* .insert({foo: 'bar'}, fn)
*
* @param {Object|Array} object
* @param {Function} callback(err, obj)
*/
Store.prototype.insert = function (object, fn) {
var store = this;
this.identify(object);
collection(this, function (err, col) {
col.insert(object, function (err, result) {
if(Array.isArray(result) && !Array.isArray(object)) {
result = result[0];
}
fn(err, store.identify(result));
});
});
};
/**
* Find the number of objects in the store that match the given query.
*
* Example:
*
* db
* .connect({host: 'localhost', port: 27015, name: 'test'})
* .createStore('testing-store')
* .count({foo: 'bar'}, fn)
*
* @param {Object} query
* @param {Function} callback(err, num)
*/
Store.prototype.count = function(query, fn) {
var store = this;
if (typeof query == 'function') {
fn = query;
query = {};
} else {
query && this.scrubQuery(query);
}
var fields = stripFields(query)
, options = stripOptions(query);
collection(this, function (err, col) {
if (err) return fn(err);
col.find(query, fields, options).count(function(err, count) {
if (err) return fn(err);
fn(null, count);
});
});
};
/**
* Find all objects in the store that match the given query.
*
* Example:
*
* db
* .connect({host: 'localhost', port: 27015, name: 'test'})
* .createStore('testing-store')
* .find({foo: 'bar'}, fn)
*
* @param {Object} query
* @param {Function} callback(err, obj)
*/
Store.prototype.find = function (query, fn) {
var store = this;
if(typeof query == 'function') {
fn = query;
query = {};
} else {
query && this.scrubQuery(query);
}
// fields
var fields = stripFields(query)
, options = stripOptions(query);
collection(this, function (err, col) {
if(typeof query._id === 'string') {
if(fields) {
col.findOne(query, fields, options, function (err, obj) {
store.identify(query);
fn(err, store.identify(obj));
});
} else {
col.findOne(query, options, function (err, obj) {
store.identify(query);
fn(err, store.identify(obj));
});
}
} else {
if(fields) {
col.find(query, fields, options).toArray(function (err, arr) {
fn(err, store.identify(arr));
});
} else {
col.find(query, options).toArray(function (err, arr) {
fn(err, store.identify(arr));
});
}
}
});
};
/**
* Find the first object in the store that match the given query.
*
* Example:
*
* db
* .connect({host: 'localhost', port: 27015, name: 'test'})
* .createStore('testing-store')
* .first({foo: 'bar'}, fn)
*
* @param {Object} query
* @param {Function} callback(err, obj)
*/
Store.prototype.first = function (query, fn) {
query && this.scrubQuery(query);
var store = this
, fields = stripFields(query);
collection(this, function (err, col) {
if(fields) {
col.findOne(query, fields, function (err, result) {
fn(err, store.identify(result));
});
} else {
col.findOne(query, function (err, result) {
fn(err, store.identify(result));
});
}
});
};
/**
* Update an object or objects in the store that match the given query.
*
* Example:
*
* db
* .connect({host: 'localhost', port: 27015, name: 'test'})
* .createStore('testing-store')
* .update({id: '<an object id>'}, fn)
*
* @param {Object} query
* @param {Object} object
* @param {Function} callback(err, obj)
*/
Store.prototype.update = function (query, object, fn) {
var store = this
, multi = false
, command = {};
if(typeof query == 'string') query = {id: query};
if(typeof query != 'object') throw new Error('update requires a query object or string id');
if(query.id) {
store.identify(query);
} else {
multi = true;
}
stripFields(query);
//Move $ queries outside of the $set command
Object.keys(object).forEach(function(k) {
if (k.indexOf('$') === 0) {
command[k] = object[k];
delete object[k];
}
});
if(Object.keys(object).length) {
command.$set = object;
}
multi = query._id ? false : true;
debug('update - query', query);
debug('update - object', object);
debug('update - command', command);
collection(this, function (err, col) {
col.update(query, command, {multi: multi}, function(err) {
store.identify(query);
fn(err);
}, multi);
});
};
/**
* Remove an object or objects in the store that match the given query.
*
* Example:
*
* db
* .connect({host: 'localhost', port: 27015, name: 'test'})
* .createStore('testing-store')
* .remove({id: '<an object id>'}, fn)
*
* @param {Object} query
* @param {Function} callback(err, obj)
*/
Store.prototype.remove = function (query, fn) {
var store = this;
if(typeof query === 'string') query = {id: query};
if(typeof query == 'function') {
fn = query;
query = {};
}
if(query.id) {
store.identify(query);
}
collection(this, function (err, col) {
col.remove(query, fn);
});
};
/**
* Rename the store.
*
* Example:
*
* db
* .connect({host: 'localhost', port: 27015, name: 'test'})
* .createStore('testing-store')
* .rename('renamed-store', fn)
*
* @param {String} namespace
* @param {Function} callback(err, obj)
*/
Store.prototype.rename = function (namespace, fn) {
var store = this;
collection(this, function (err, col) {
store.namespace = namespace;
col.rename(namespace, fn);
});
};
function stripFields(query) {
if(!query) return;
var fields = query.$fields;
if(fields) delete query.$fields;
return fields;
}
function stripOptions(query) {
var options = {};
if(!query) return options;
// performance
if(query.$limit) options.limit = query.$limit;
if(query.$skip) options.skip = query.$skip;
if(query.$sort || query.$orderby) options.sort = query.$sort || query.$orderby;
delete query.$limit;
delete query.$skip;
delete query.$sort;
return options;
}