-
Notifications
You must be signed in to change notification settings - Fork 20
/
index.js
673 lines (532 loc) · 18.1 KB
/
index.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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
/**
* Module dependencies
*/
var nano = require('nano');
var async = require('async');
var extend = require('xtend');
var cookie = require('cookie');
var DeepMerge = require('deep-merge');
var _ = require('underscore');
var merge = DeepMerge(function(a, b) {
return b;
});
var registry = require('./registry');
var views = require('./views');
// You'll want to maintain a reference to each collection
// (aka model) that gets registered with this adapter.
var adapter = exports;
// Set to true if this adapter supports (or requires) things like data types, validations, keys, etc.
// If true, the schema for models using this adapter will be automatically synced when the server starts.
// Not terribly relevant if your data store is not SQL/schemaful.
adapter.syncable = false;
// Reserved attributes.
// These attributes get passed in to the `adapter.update` function even if they're not declared
// in the model schema.
adapter.reservedAttributes = ['id', 'rev'];
// Default configuration for collections
// (same effect as if these properties were included at the top level of the model definitions)
adapter.defaults = {
port: 5984,
host: 'localhost',
https: false,
username: null,
password: null,
schema: true,
syncable: false,
autoPK: false,
pkFormat: 'string',
maxMergeAttempts: 5,
// If setting syncable, you should consider the migrate option,
// which allows you to set how the sync will be performed.
// It can be overridden globally in an app (config/adapters.js)
// and on a per-model basis.
//
// IMPORTANT:
// `migrate` is not a production data migration solution!
// In production, always use `migrate: safe`
//
// drop => Drop schema and data, then recreate it
// alter => Drop/add columns as necessary.
// safe => Don't change anything (good for production DBs)
migrate: 'safe'
};
/**
*
* This method runs when a model is initially registered
* at server-start-time. This is the only required method.
*
* @param {[type]} collection [description]
* @param {Function} cb [description]
* @return {[type]} [description]
*/
adapter.registerConnection = function registerConnection(connection, collections, cb) {
var url = urlForConfig(connection);
var db = nano(url);
// Save the connection
registry.connection(connection.identity, connection);
async.each(_.keys(collections),function(modelIdentity,next) {
adapter.registerSingleCollection(connection, modelIdentity, collections[modelIdentity], next);
}, function afterAsyncEach (err) {
if(err) {
return cb(new Error(err.description));
}
return cb();
});
};
/**
*
* This method runs to register a single model, or collection.
*
* @param {[type]} connection [description]
* @param {[type]} collection [description]
* @param {Function} cb [description]
* @return {[type]} [description]
*/
adapter.registerSingleCollection = function registerCollection(connection, collectionName, collection, cb) {
collectionName = sanitizeCollectionName(collectionName);
var url = urlForConfig(connection);
// Wire up nano to the configured couchdb connection
var db = nano(url);
// console.log('registering %s', collectionName);
// console.log('got db.db or whatever', db);
// console.log('urlForConfig', url,connection);
db.db.get(collectionName, function gotDatabase(err) {
// No error means we're good! The collection (or in couch terms, the "db")
// is already known and ready to use.
if (!err) {
registry.collection(collectionName, collection);
registry.db(collectionName, nano(url + collectionName));
return cb();
}
try {
if (err.status_code == 404 && err.reason == 'no_db_file') {
db.db.create(collectionName, function createdDB(err) {
if (err) {
return cb(err);
}
adapter.registerSingleCollection(connection, collectionName, collection, cb);
});
return;
}
// console.log('unexpected ERROR', err);
return cb(err);
}
catch (e) { return cb(e); }
});
};
/**
* Fired when a model is unregistered, typically when the server
* is killed. Useful for tearing-down remaining open connections,
* etc.
*
* @param {Function} cb [description]
* @return {[type]} [description]
*/
adapter.teardown = function teardown(connection, cb) {
process.nextTick(cb);
};
/**
*
* REQUIRED method if integrating with a schemaful
* (SQL-ish) database.
*
* @param {[type]} collectionName [description]
* @param {Function} cb [description]
* @return {[type]} [description]
*/
adapter.describe = function describe(connection, collectionName, cb) {
collectionName = sanitizeCollectionName(collectionName);
var collection = registry.collection(collectionName);
if (! collection)
return cb(new Error('no such collection'));
return cb(null, collection.definition);
};
/**
*
*
* REQUIRED method if integrating with a schemaful
* (SQL-ish) database.
*
* @param {[type]} collectionName [description]
* @param {[type]} relations [description]
* @param {Function} cb [description]
* @return {[type]} [description]
*/
adapter.drop = function drop(connectionName, collectionName, relations, cb) {
collectionName = sanitizeCollectionName(collectionName);
var connection = registry.connection(connectionName);
var url = urlForConfig(connection);
var db = nano(url);
db.db.destroy(collectionName, cb);
};
/**
* REQUIRED method if users expect to call Model.find(), Model.findOne(),
* or related.
*
* You should implement this method to respond with an array of instances.
* Waterline core will take care of supporting all the other different
* find methods/usages.
*
* @param {[type]} connectionName [description]
* @param {[type]} collectionName [description]
* @param {[type]} criteria [description]
* @param {Function} cb [description]
* @return {[type]} [description]
*/
adapter.find = find;
function find(connectionName, collectionName, criteria, cb, round) {
collectionName = sanitizeCollectionName(collectionName);
if ('number' != typeof round) round = 0;
// If you need to access your private data for this collection:
var db = registry.db(collectionName);
console.log('GETTING DB FOR "%s"."%s"', connectionName, collectionName);
// console.log('got: ',db);
if (!db) {
return cb((function buildError(){
var e = new Error();
e.name = 'Adapter Error';
e.type = 'adapter';
e.code = 'E_ADAPTER';
e.message = util.format('Could not acquire data access object (`db`) object for CouchDB connection "%s" for collection "%s"', connectionName, collectionName);
e.connectionName = connectionName;
e.collectionName = collectionName;
return e;
})());
}
// Build initial `dbOptions`
var dbOptions = (function (dbOptions){
if (criteria.limit) dbOptions.limit = criteria.limit;
if (criteria.skip) dbOptions.skip = criteria.skip;
return dbOptions;
})({});
var queriedAttributes = Object.keys(criteria.where || {});
//console.log("Queried Attributes: ",queriedAttributes);
// Handle case where no criteria is specified at all
// (list all documents in the couch collection)
if (queriedAttributes.length === 0) {
console.log('Queried Attributes" (aka criteria\'s WHERE clause) doesn\'t contain any values-- listing everything!');
// All docs
dbOptions.include_docs = true;
// TODO: test if limit works?
// TODO: test if skip works?
// TODO: test if sort works?
db.list(dbOptions, function listReplied(err, docs) {
if (err) {
return cb(err);
}
if (!Array.isArray(docs) && docs.rows) {
docs = docs.rows.map(prop('doc'));
}
else {}
// either way...
return cb(null, docs.map(docForReply));
});
return;
}
// Handle query for a single doc using the provided primary key criteria (e.g. `findOne()`)
if (queriedAttributes.length == 1 && (queriedAttributes[0] == 'id' || queriedAttributes[0] == '_id')) {
var id = criteria.where.id || criteria.where._id;
db.get(id, dbOptions, function(err, doc) {
if (err) {
if (err.status_code == 404) {
return cb(null, []);
}
return cb(err);
}
var docs = doc ? [doc] : [];
return cb(null, docs.map(docForReply));
});
return;
}
// Take a look at `criteria.where.like`...
asyncx_ifTruthy(criteria.where.like,
// Handle "like" modifier using a view
function ifSoDo(next){
var viewName = views.name(criteria.where.like);
var value = views.likeValue(criteria.where.like, true);
dbOptions.startkey = value.startkey;
dbOptions.endkey = value.endkey;
return db.view('views', viewName, dbOptions, next);
},
// Handle general-case criteria queries using a view
function elseDo (next){
var viewName = views.name(criteria.where);
dbOptions.key = views.value(criteria.where);
return db.view('views', viewName, dbOptions, next);
},
function finallyDo(err, reply) {
if (err) {
if (err.status_code === 404 && round < 1) {
views.create(db, criteria.where.like || criteria.where, function createdView(err) {
if (err) {
return cb(err);
}
find.call(connectionName, connectionName, collectionName, criteria, cb, round + 1);
});
return;
}
return cb(err);
}
return cb(null, reply.rows.map(prop('value')).map(docForReply));
}
);
}
/**
*
* REQUIRED method if users expect to call Model.create() or any methods
*
* @param {[type]} collectionName [description]
* @param {[type]} values [description]
* @param {Function} cb [description]
* @return {[type]} [description]
*/
adapter.create = function create(connectionName, collectionName, values, cb) {
collectionName = sanitizeCollectionName(collectionName);
var db = registry.db(collectionName);
db.insert(docForIngestion(values), replied);
function replied(err, reply) {
if (err) cb(err);
else {
var attrs = extend({}, values, { _id: reply.id, _rev: reply.rev });
cb(null, docForReply(attrs));
}
}
};
/**
*
*
* REQUIRED method if users expect to call Model.update()
*
* @param {[type]} collectionName [description]
* @param {[type]} options [description]
* @param {[type]} values [description]
* @param {Function} cb [description]
* @return {[type]} [description]
*/
adapter.update = function update(connectionName, collectionName, options, values, cb) {
collectionName = sanitizeCollectionName(collectionName);
var searchAttributes = Object.keys(options.where);
if (searchAttributes.length != 1)
return cb(new Error('only support updating one object by id'));
if (searchAttributes[0] != 'id')
return cb(new Error('only support updating one object by id'));
// Find the document
adapter.find(connectionName, collectionName, options, function(err,docs) {
var doc = docs[0]; // only one document with that id
if(!doc) return cb('No document found to update.');
delete values.id; // deleting id from values attr
Object.keys(values).forEach(function(key) {
doc[key] = values[key];
});
//console.log('Document to update: ', doc);
var db = registry.db(collectionName);
db.insert(docForIngestion(doc), options.where.id, function(err, reply) {
if (err) cb(err);
else {
var attrs = extend({}, doc, { _id: reply.id, _rev: reply.rev });
cb(null, docForReply(attrs));
}
});
});
};
/**
*
* REQUIRED method if users expect to call Model.destroy()
*
* @param {[type]} collectionName [description]
* @param {[type]} options [description]
* @param {Function} cb [description]
* @return {[type]} [description]
*/
adapter.destroy = function destroy(connectionName, collectionName, options, cb) {
collectionName = sanitizeCollectionName(collectionName);
var db = registry.db(collectionName);
// Find the record
adapter.find(connectionName,collectionName,options, function(err,docs) {
async.each(docs,function(item) { // Shoud have only one.
db.destroy(item.id, item.rev, function(err, doc) {
cb(err,[item]); // Waterline expects an array as result.
});
});
});
};
/**********************************************
* Custom methods
**********************************************/
/// Authenticate
adapter.authenticate = function authenticate(connection, collectionName, username, password, cb) {
collectionName = sanitizeCollectionName(collectionName);
var db = registry.db(collectionName);
db.auth(username, password, replied);
function replied(err, body, headers) {
if (err) cb(err);
else {
var sessionId;
var header = headers['set-cookie'][0];
if (header) sessionId = cookie.parse(header).AuthSession;
cb(null, sessionId, username, body.roles);
}
}
};
/// Session
adapter.session = function session(connection, collectionName, sid, cb) {
collectionName = sanitizeCollectionName(collectionName);
var url = urlForConfig(registry.connection(connection));
var sessionDb = nano({
url: url,
cookie: 'AuthSession=' + encodeURIComponent(sid)
});
sessionDb.session(cb);
};
/// Merge
adapter.merge = function adapterMerge(connectionName, collectionName, id, attrs, cb, attempts) {
collectionName = sanitizeCollectionName(collectionName);
var doc;
var db = registry.db(collectionName);
var coll = registry.collection(collectionName);
/*
console.log('------------------------------------------');
console.log('Attempting merge on ',collectionName,id,attrs);
console.log('------------------------------------------');
*/
if ('number' != typeof attempts) attempts = 0;
else if (attempts > 0) {
//var config = coll.adapter.config;
// Reference to maxMergeAttempts
if (attempts > 5) {
return cb(new Error('max attempts of merging reached'));
}
}
db.get(id, got);
function got(err, _doc) {
if (err && err.status_code == 404) _doc = {};
else if (err) return cb(err);
delete attrs._rev;
_doc = docForReply(_doc);
doc = merge(_doc, attrs);
//console.log('----------Callbacks',coll._callbacks.beforeUpdate);
async.eachSeries(coll._callbacks.beforeUpdate || [], invokeCallback, afterBeforeUpdate);
}
function invokeCallback(fn, cb) {
//console.log("----------Calling Function ",fn);
fn.call(null, doc, cb);
}
function afterBeforeUpdate(err) {
if (err) return cb(err);
var newdoc = docForIngestion(doc);
//console.log('----------Heres our final doc',newdoc._id,newdoc._rev);
console.trace();
db.insert(newdoc, id, saved);
}
function saved(err, reply) {
if (err && err.status_code == 409) {
//console.log('Calling merge again!');
adapter.merge(connectionName, collectionName, id, attrs, cb, attempts + 1);
}
else if (err) cb(err);
else {
extend(doc, { _rev: reply.rev, _id: reply.id });
doc = docForReply(doc);
callbackAfter();
}
}
function callbackAfter() {
async.eachSeries(coll._callbacks.afterUpdate || [], invokeCallback, finalCallback);
}
function finalCallback(err) {
if (err) cb(err);
else cb(null, doc);
}
};
/// View
adapter.view = function view(connectionName, collectionName, viewName, options, cb, round) {
collectionName = sanitizeCollectionName(collectionName);
if ('number' != typeof round) round = 0;
var db = registry.db(collectionName);
db.view('views', viewName, options, viewResult);
function viewResult(err, results) {
if (err && err.status_code == 404 && round < 2)
populateView(connectionName, collectionName, viewName, populatedView);
else if (err) cb(err);
else cb(null, (results && results.rows && results.rows || []).map(prop('value')).map(docForReply));
}
function populatedView(err) {
if (err) cb(err);
else adapter.view(connectionName, collectionName, viewName, options, cb, round + 1);
}
};
function populateView(connectionName, collectionName, viewName, cb) {
collectionName = sanitizeCollectionName(collectionName);
var collection = registry.collection(collectionName);
var view = collection.views && collection.views[viewName];
if (! view) return cb(new Error('No view named ' + viewName + ' defined in model ' + collectionName));
else {
var db = registry.db(collectionName);
db.get('_design/views', gotDDoc);
}
function gotDDoc(err, ddoc) {
if (! ddoc) ddoc = {};
if (! ddoc.views) ddoc.views = {};
if (! ddoc._id) ddoc._id = '_design/views';
ddoc.views[viewName] = view;
ddoc.language = 'javascript';
db.insert(ddoc, insertedDDoc);
}
function insertedDDoc(err) {
cb(err);
}
}
/// Utils
function urlForConfig(config) {
var schema = 'http';
if (config.https) schema += 's';
var auth = '';
if (config.username && config.password) {
auth = encodeURIComponent(config.username) + ':' + encodeURIComponent(config.password) + '@';
}
return [schema, '://', auth, config.host, ':', config.port, '/'].join('');
}
function prop(p) {
return function(o) {
return o[p];
};
}
function docForReply(doc) {
if (doc._id) {
doc.id = doc._id;
delete doc._id;
}
if (doc._rev) {
doc.rev = doc._rev;
delete doc._rev;
}
return doc;
}
function docForIngestion(doc) {
doc = extend({}, doc);
if (doc.id) {
doc._id = doc.id;
delete doc.id;
}
if (doc.rev) {
doc._rev = doc.rev;
delete doc.rev;
}
return doc;
}
/**
* Branch to the appropriate fn if the provided value is truthy.
*
* @param {*} valToTest
* @param {Function} ifSoDo(next)
* @param {Function} elseDo(next)
* @param {Function} finallyDo(err, results)
*/
function asyncx_ifTruthy (valToTest, ifSoDo, elseDo, finallyDo){
return (valToTest ? ifSoDo : elseDo)(finallyDo);
}
function sanitizeCollectionName (collectionName) {
return collectionName.replace(/([A-Z])/g, function (c) {
return c.toLowerCase();
});
}