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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002 |
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
15×
1×
1×
1×
1×
1×
1×
77×
77×
22×
55×
73×
73×
1×
5533×
32×
5501×
3000×
2501×
1×
16994×
16649×
345×
1195×
1195×
201×
201×
1×
2967×
2967×
1×
2967×
2967×
2967×
2966×
2967×
2967×
1×
23669×
1×
24973×
24973×
1×
6983×
11771×
1×
2967×
2967×
2967×
1×
2967×
2967×
2967×
2967×
2967×
1×
2967×
1×
2967×
4×
4×
4×
4×
1×
22666×
22666×
22666×
22666×
1×
8775×
8775×
8775×
2566×
6209×
1×
29670×
8903×
8874×
29×
29×
2967×
1×
17498×
4×
17494×
16205×
1289×
1289×
1150×
1126×
1126×
24×
31×
1×
30×
1289×
30×
1289×
2967×
2967×
2967×
5958×
2967×
1106×
1106×
1106×
2967×
586×
586×
2967×
583×
581×
581×
583×
583×
1×
1171×
1171×
583×
588×
583×
2967×
198×
1×
1×
1×
1×
1×
1×
1×
1×
198×
198×
198×
198×
1×
208×
208×
208×
198×
198×
208×
208×
208×
198×
198×
198×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
197×
1×
197×
2967×
1549×
1548×
1548×
1×
1548×
1548×
2967×
4084×
3404×
3404×
4084×
4084×
4084×
371×
4084×
10×
4084×
300×
238×
300×
4084×
178×
4084×
129×
4084×
4084×
1×
903×
903×
903×
762×
141×
1171×
1171×
1171×
1171×
7×
1164×
1171×
1171×
1171×
1×
305×
229×
828×
827×
76×
4084×
2679×
2679×
305×
2679×
2967×
111×
111×
22×
22×
20×
20×
89×
89×
86×
86×
3×
3×
111×
111×
1×
1338×
2967×
32×
24×
24×
32×
32×
32×
2967×
3×
3×
2967×
132×
4×
4×
4×
4×
132×
132×
132×
123×
132×
16×
16×
16×
1×
15×
131×
131×
2967×
5253×
5253×
5253×
5253×
5253×
19×
5234×
13450×
5234×
2967×
1105×
74×
74×
1105×
1105×
1105×
1105×
1105×
1×
1105×
6×
1105×
938×
1105×
33×
1105×
17×
1105×
1×
1105×
43×
1105×
1×
1105×
22×
1105×
9×
1105×
46×
1105×
25×
1105×
1105×
902×
902×
901×
1×
1×
1105×
1101×
9×
1101×
2967×
1425×
1425×
1425×
1425×
1425×
1425×
1425×
1215×
210×
1×
209×
1425×
1425×
1254×
1425×
119×
1425×
16×
1425×
198×
1425×
14×
1425×
22×
1425×
4×
3×
1421×
1425×
56×
56×
10×
1425×
23×
23×
23×
1425×
1425×
1425×
37×
37×
37×
35×
2×
2×
1425×
1425×
1425×
1844×
51×
1793×
1793×
1×
1793×
22×
8×
1771×
1793×
1793×
1793×
1×
1793×
1793×
1425×
1425×
1659×
17×
1642×
1642×
1626×
1626×
1626×
1626×
1626×
2418×
2418×
2418×
2403×
47×
2403×
2383×
2403×
2418×
16×
12×
12×
12×
1630×
1604×
1630×
1630×
419×
419×
1211×
1425×
1425×
377×
377×
360×
2967×
1132×
1131×
1131×
1132×
2967×
7×
2967×
1612×
1612×
1×
1611×
1611×
1611×
1×
5936×
1×
1× | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jsExtend = require('js-extend');
var _pick = require('../../deps/pick');
var _pick2 = _interopRequireDefault(_pick);
var _filterChange = require('../../deps/filterChange');
var _filterChange2 = _interopRequireDefault(_filterChange);
var _adapterFun = require('../../deps/adapterFun');
var _adapterFun2 = _interopRequireDefault(_adapterFun);
var _explainError = require('../../deps/ajax/explainError');
var _explainError2 = _interopRequireDefault(_explainError);
var _binaryStringToBlobOrBuffer = require('../../deps/binary/binaryStringToBlobOrBuffer');
var _binaryStringToBlobOrBuffer2 = _interopRequireDefault(_binaryStringToBlobOrBuffer);
var _base64StringToBlobOrBuffer = require('../../deps/binary/base64StringToBlobOrBuffer');
var _base64StringToBlobOrBuffer2 = _interopRequireDefault(_base64StringToBlobOrBuffer);
var _utils = require('../../utils');
var _utils2 = _interopRequireDefault(_utils);
var _promise = require('../../deps/promise');
var _promise2 = _interopRequireDefault(_promise);
var _clone = require('../../deps/clone');
var _clone2 = _interopRequireDefault(_clone);
var _parseUri = require('../../deps/parseUri');
var _parseUri2 = _interopRequireDefault(_parseUri);
var _argsarray = require('argsarray');
var _argsarray2 = _interopRequireDefault(_argsarray);
var _base = require('../../deps/binary/base64');
var _errors = require('../../deps/errors');
var _debug = require('debug');
var _debug2 = _interopRequireDefault(_debug);
var _blobOrBufferToBase = require('../../deps/binary/blobOrBufferToBase64');
var _blobOrBufferToBase2 = _interopRequireDefault(_blobOrBufferToBase);
var _bulkGetShim = require('../../deps/bulkGetShim');
var _bulkGetShim2 = _interopRequireDefault(_bulkGetShim);
var _flatten = require('../../deps/flatten');
var _flatten2 = _interopRequireDefault(_flatten);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var CHANGES_BATCH_SIZE = 25;
var MAX_SIMULTANEOUS_REVS = 50;
var supportsBulkGetMap = {};
// according to http://stackoverflow.com/a/417184/680742,
// the de facto URL length limit is 2000 characters.
// but since most of our measurements don't take the full
// URL into account, we fudge it a bit.
// TODO: we could measure the full URL to enforce exactly 2000 chars
var MAX_URL_LENGTH = 1800;
var log = (0, _debug2.default)('pouchdb:http');
function readAttachmentsAsBlobOrBuffer(row) {
var atts = row.doc && row.doc._attachments;
if (!atts) {
return;
}
Object.keys(atts).forEach(function (filename) {
var att = atts[filename];
att.data = (0, _base64StringToBlobOrBuffer2.default)(att.data, att.content_type);
});
}
function encodeDocId(id) {
if (/^_design/.test(id)) {
return '_design/' + encodeURIComponent(id.slice(8));
}
if (/^_local/.test(id)) {
return '_local/' + encodeURIComponent(id.slice(7));
}
return encodeURIComponent(id);
}
function preprocessAttachments(doc) {
if (!doc._attachments || !Object.keys(doc._attachments)) {
return _promise2.default.resolve();
}
return _promise2.default.all(Object.keys(doc._attachments).map(function (key) {
var attachment = doc._attachments[key];
if (attachment.data && typeof attachment.data !== 'string') {
return (0, _blobOrBufferToBase2.default)(attachment.data).then(function (b64) {
attachment.data = b64;
});
}
}));
}
// Get all the information you possibly can about the URI given by name and
// return it as a suitable object.
function getHost(name) {
// Prase the URI into all its little bits
var uri = (0, _parseUri2.default)(name);
// Store the user and password as a separate auth object
if (uri.user || uri.password) {
uri.auth = { username: uri.user, password: uri.password };
}
// Split the path part of the URI into parts using '/' as the delimiter
// after removing any leading '/' and any trailing '/'
var parts = uri.path.replace(/(^\/|\/$)/g, '').split('/');
// Store the first part as the database name and remove it from the parts
// array
uri.db = parts.pop();
// Prevent double encoding of URI component
if (uri.db.indexOf('%') === -1) {
uri.db = encodeURIComponent(uri.db);
}
// Restore the path by joining all the remaining parts (all the parts
// except for the database name) with '/'s
uri.path = parts.join('/');
return uri;
}
// Generate a URL with the host data given by opts and the given path
function genDBUrl(opts, path) {
return genUrl(opts, opts.db + '/' + path);
}
// Generate a URL with the host data given by opts and the given path
function genUrl(opts, path) {
// If the host already has a path, then we need to have a path delimiter
// Otherwise, the path delimiter is the empty string
var pathDel = !opts.path ? '' : '/';
// If the host already has a path, then we need to have a path delimiter
// Otherwise, the path delimiter is the empty string
return opts.protocol + '://' + opts.host + (opts.port ? ':' + opts.port : '') + '/' + opts.path + pathDel + path;
}
function paramsToStr(params) {
return '?' + Object.keys(params).map(function (k) {
return k + '=' + encodeURIComponent(params[k]);
}).join('&');
}
// Implements the PouchDB API for dealing with CouchDB instances over HTTP
function HttpPouch(opts, callback) {
// The functions that will be publicly available for HttpPouch
var api = this;
// Parse the URI given by opts.name into an easy-to-use object
var getHostFun = getHost;
// TODO: this seems to only be used by yarong for the Thali project.
// Verify whether or not it's still needed.
/* istanbul ignore if */
Iif (opts.getHost) {
getHostFun = opts.getHost;
}
var host = getHostFun(opts.name, opts);
var dbUrl = genDBUrl(host, '');
opts = (0, _clone2.default)(opts);
var ajaxOpts = opts.ajax || {};
api.getUrl = function () {
return dbUrl;
};
api.getHeaders = function () {
return ajaxOpts.headers || {};
};
if (opts.auth || host.auth) {
var nAuth = opts.auth || host.auth;
var token = (0, _base.btoa)(nAuth.username + ':' + nAuth.password);
ajaxOpts.headers = ajaxOpts.headers || {};
ajaxOpts.headers.Authorization = 'Basic ' + token;
}
function ajax(userOpts, options, callback) {
var reqAjax = userOpts.ajax || {};
var reqOpts = (0, _jsExtend.extend)((0, _clone2.default)(ajaxOpts), reqAjax, options);
log(reqOpts.method + ' ' + reqOpts.url);
return _utils2.default.ajax(reqOpts, callback);
}
function ajaxPromise(userOpts, opts) {
return new _promise2.default(function (resolve, reject) {
ajax(userOpts, opts, function (err, res) {
if (err) {
return reject(err);
}
resolve(res);
});
});
}
function adapterFun(name, fun) {
return (0, _adapterFun2.default)(name, (0, _argsarray2.default)(function (args) {
setup().then(function (res) {
return fun.apply(this, args);
}).catch(function (e) {
var callback = args.pop();
callback(e);
});
}));
}
var setupPromise;
function setup() {
// TODO: Remove `skipSetup` in favor of `skip_setup` in a future release
if (opts.skipSetup || opts.skip_setup) {
return _promise2.default.resolve();
}
// If there is a setup in process or previous successful setup
// done then we will use that
// If previous setups have been rejected we will try again
if (setupPromise) {
return setupPromise;
}
var checkExists = { method: 'GET', url: dbUrl };
setupPromise = ajaxPromise({}, checkExists).catch(function (err) {
if (err && err.status && err.status === 404) {
// Doesnt exist, create it
(0, _explainError2.default)(404, 'PouchDB is just detecting if the remote exists.');
return ajaxPromise({}, { method: 'PUT', url: dbUrl });
} else {
return _promise2.default.reject(err);
}
}).catch(function (err) {
// If we try to create a database that already exists
if (err && err.status && err.status === 412) {
return true;
}
return _promise2.default.reject(err);
});
setupPromise.catch(function () {
setupPromise = null;
});
return setupPromise;
}
setTimeout(function () {
callback(null, api);
});
api.type = function () {
return 'http';
};
api.id = adapterFun('id', function (callback) {
ajax({}, { method: 'GET', url: genUrl(host, '') }, function (err, result) {
var uuid = result && result.uuid ? result.uuid + host.db : genDBUrl(host, '');
callback(null, uuid);
});
});
api.request = adapterFun('request', function (options, callback) {
options.url = genDBUrl(host, options.url);
ajax({}, options, callback);
});
// Sends a POST request to the host calling the couchdb _compact function
// version: The version of CouchDB it is running
api.compact = adapterFun('compact', function (opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
opts = (0, _clone2.default)(opts);
ajax(opts, {
url: genDBUrl(host, '_compact'),
method: 'POST'
}, function () {
function ping() {
api.info(function (err, res) {
if (res && !res.compact_running) {
callback(null, { ok: true });
} else {
setTimeout(ping, opts.interval || 200);
}
});
}
// Ping the http if it's finished compaction
ping();
});
});
api.bulkGet = (0, _adapterFun2.default)('bulkGet', function (opts, callback) {
var self = this;
function doBulkGet(cb) {
var params = {};
Eif (opts.revs) {
params.revs = true;
}
Eif (opts.attachments) {
params.attachments = true;
}
ajax({}, {
url: genDBUrl(host, '_bulk_get' + paramsToStr(params)),
method: 'POST',
body: { docs: opts.docs }
}, cb);
}
function doBulkGetShim() {
// avoid "url too long error" by splitting up into multiple requests
var batchSize = MAX_SIMULTANEOUS_REVS;
var numBatches = Math.ceil(opts.docs.length / batchSize);
var numDone = 0;
var results = new Array(numBatches);
function onResult(batchNum) {
return function (err, res) {
// err is impossible because shim returns a list of errs in that case
results[batchNum] = res.results;
if (++numDone === numBatches) {
callback(null, { results: (0, _flatten2.default)(results) });
}
};
}
for (var i = 0; i < numBatches; i++) {
var subOpts = (0, _pick2.default)(opts, ['revs', 'attachments']);
subOpts.docs = opts.docs.slice(i * batchSize, Math.min(opts.docs.length, (i + 1) * batchSize));
(0, _bulkGetShim2.default)(self, subOpts, onResult(i));
}
}
// mark the whole database as either supporting or not supporting _bulk_get
var dbUrl = genUrl(host, '');
var supportsBulkGet = supportsBulkGetMap[dbUrl];
if (typeof supportsBulkGet !== 'boolean') {
// check if this database supports _bulk_get
doBulkGet(function (err, res) {
/* istanbul ignore else */
Eif (err) {
var status = Math.floor(err.status / 100);
/* istanbul ignore else */
Eif (status === 4 || status === 5) {
// 40x or 50x
supportsBulkGetMap[dbUrl] = false;
(0, _explainError2.default)(err.status, 'PouchDB is just detecting if the remote ' + 'supports the _bulk_get API.');
doBulkGetShim();
} else {
callback(err);
}
} else {
supportsBulkGetMap[dbUrl] = true;
callback(null, res);
}
});
} else Iif (supportsBulkGet) {
/* istanbul ignore next */
doBulkGet(callback);
} else {
doBulkGetShim();
}
});
// Calls GET on the host, which gets back a JSON string containing
// couchdb: A welcome string
// version: The version of CouchDB it is running
api._info = function (callback) {
setup().then(function () {
ajax({}, {
method: 'GET',
url: genDBUrl(host, '')
}, function (err, res) {
/* istanbul ignore next */
Iif (err) {
return callback(err);
}
res.host = genDBUrl(host, '');
callback(null, res);
});
}).catch(callback);
};
// Get the document with the given id from the database given by host.
// The id could be solely the _id in the database, or it may be a
// _design/ID or _local/ID path
api.get = adapterFun('get', function (id, opts, callback) {
// If no options were given, set the callback to the second parameter
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
opts = (0, _clone2.default)(opts);
// List of parameters to add to the GET request
var params = {};
if (opts.revs) {
params.revs = true;
}
if (opts.revs_info) {
params.revs_info = true;
}
if (opts.open_revs) {
if (opts.open_revs !== "all") {
opts.open_revs = JSON.stringify(opts.open_revs);
}
params.open_revs = opts.open_revs;
}
if (opts.rev) {
params.rev = opts.rev;
}
if (opts.conflicts) {
params.conflicts = opts.conflicts;
}
id = encodeDocId(id);
// Set the options for the ajax call
var options = {
method: 'GET',
url: genDBUrl(host, id + paramsToStr(params))
};
function fetchAttachments(doc) {
var atts = doc._attachments;
var filenames = atts && Object.keys(atts);
if (!atts || !filenames.length) {
return;
}
// we fetch these manually in separate XHRs, because
// Sync Gateway would normally send it back as multipart/mixed,
// which we cannot parse. Also, this is more efficient than
// receiving attachments as base64-encoded strings.
return _promise2.default.all(filenames.map(function (filename) {
var att = atts[filename];
var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) + '?rev=' + doc._rev;
return ajaxPromise(opts, {
method: 'GET',
url: genDBUrl(host, path),
binary: true
}).then(function (blob) {
if (opts.binary) {
return blob;
}
return (0, _blobOrBufferToBase2.default)(blob);
}).then(function (data) {
delete att.stub;
delete att.length;
att.data = data;
});
}));
}
function fetchAllAttachments(docOrDocs) {
if (Array.isArray(docOrDocs)) {
return _promise2.default.all(docOrDocs.map(function (doc) {
if (doc.ok) {
return fetchAttachments(doc.ok);
}
}));
}
return fetchAttachments(docOrDocs);
}
ajaxPromise(opts, options).then(function (res) {
return _promise2.default.resolve().then(function () {
if (opts.attachments) {
return fetchAllAttachments(res);
}
}).then(function () {
callback(null, res);
});
}).catch(callback);
});
// Delete the document given by doc from the database given by host.
api.remove = adapterFun('remove', function (docOrId, optsOrRev, opts, callback) {
var doc;
if (typeof optsOrRev === 'string') {
// id, rev, opts, callback style
doc = {
_id: docOrId,
_rev: optsOrRev
};
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
} else {
// doc, opts, callback style
doc = docOrId;
if (typeof optsOrRev === 'function') {
callback = optsOrRev;
opts = {};
} else {
callback = opts;
opts = optsOrRev;
}
}
var rev = doc._rev || opts.rev;
// Delete the document
ajax(opts, {
method: 'DELETE',
url: genDBUrl(host, encodeDocId(doc._id)) + '?rev=' + rev
}, callback);
});
function encodeAttachmentId(attachmentId) {
return attachmentId.split("/").map(encodeURIComponent).join("/");
}
// Get the attachment
api.getAttachment = adapterFun('getAttachment', function (docId, attachmentId, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
var params = opts.rev ? '?rev=' + opts.rev : '';
var url = genDBUrl(host, encodeDocId(docId)) + '/' + encodeAttachmentId(attachmentId) + params;
ajax(opts, {
method: 'GET',
url: url,
binary: true
}, callback);
});
// Remove the attachment given by the id and rev
api.removeAttachment = adapterFun('removeAttachment', function (docId, attachmentId, rev, callback) {
var url = genDBUrl(host, encodeDocId(docId) + '/' + encodeAttachmentId(attachmentId)) + '?rev=' + rev;
ajax({}, {
method: 'DELETE',
url: url
}, callback);
});
// Add the attachment given by blob and its contentType property
// to the document with the given id, the revision given by rev, and
// add it to the database given by host.
api.putAttachment = adapterFun('putAttachment', function (docId, attachmentId, rev, blob, type, callback) {
if (typeof type === 'function') {
callback = type;
type = blob;
blob = rev;
rev = null;
}
var id = encodeDocId(docId) + '/' + encodeAttachmentId(attachmentId);
var url = genDBUrl(host, id);
if (rev) {
url += '?rev=' + rev;
}
if (typeof blob === 'string') {
// input is assumed to be a base64 string
var binary;
try {
binary = (0, _base.atob)(blob);
} catch (err) {
return callback((0, _errors.createError)(_errors.BAD_ARG, 'Attachment is not a valid base64 string'));
}
blob = binary ? (0, _binaryStringToBlobOrBuffer2.default)(binary, type) : '';
}
var opts = {
headers: { 'Content-Type': type },
method: 'PUT',
url: url,
processData: false,
body: blob,
timeout: ajaxOpts.timeout || 60000
};
// Add the attachment
ajax({}, opts, callback);
});
// Update/create multiple documents given by req in the database
// given by host.
api._bulkDocs = function (req, opts, callback) {
// If new_edits=false then it prevents the database from creating
// new revision numbers for the documents. Instead it just uses
// the old ones. This is used in database replication.
req.new_edits = opts.new_edits;
setup().then(function () {
return _promise2.default.all(req.docs.map(preprocessAttachments));
}).then(function () {
// Update/create the documents
ajax(opts, {
method: 'POST',
url: genDBUrl(host, '_bulk_docs'),
body: req
}, function (err, results) {
if (err) {
return callback(err);
}
results.forEach(function (result) {
result.ok = true; // smooths out cloudant not adding this
});
callback(null, results);
});
}).catch(callback);
};
// Get a listing of the documents in the database given
// by host and ordered by increasing id.
api.allDocs = adapterFun('allDocs', function (opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
opts = (0, _clone2.default)(opts);
// List of parameters to add to the GET request
var params = {};
var body;
var method = 'GET';
if (opts.conflicts) {
params.conflicts = true;
}
if (opts.descending) {
params.descending = true;
}
if (opts.include_docs) {
params.include_docs = true;
}
// added in CouchDB 1.6.0
if (opts.attachments) {
params.attachments = true;
}
if (opts.key) {
params.key = JSON.stringify(opts.key);
}
if (opts.start_key) {
opts.startkey = opts.start_key;
}
if (opts.startkey) {
params.startkey = JSON.stringify(opts.startkey);
}
if (opts.end_key) {
opts.endkey = opts.end_key;
}
if (opts.endkey) {
params.endkey = JSON.stringify(opts.endkey);
}
if (typeof opts.inclusive_end !== 'undefined') {
params.inclusive_end = !!opts.inclusive_end;
}
if (typeof opts.limit !== 'undefined') {
params.limit = opts.limit;
}
if (typeof opts.skip !== 'undefined') {
params.skip = opts.skip;
}
var paramStr = paramsToStr(params);
if (typeof opts.keys !== 'undefined') {
var keysAsString = 'keys=' + encodeURIComponent(JSON.stringify(opts.keys));
if (keysAsString.length + paramStr.length + 1 <= MAX_URL_LENGTH) {
// If the keys are short enough, do a GET. we do this to work around
// Safari not understanding 304s on POSTs (see issue #1239)
paramStr += '&' + keysAsString;
} else {
// If keys are too long, issue a POST request to circumvent GET
// query string limits
// see http://wiki.apache.org/couchdb/HTTP_view_API#Querying_Options
method = 'POST';
body = { keys: opts.keys };
}
}
// Get the document listing
ajaxPromise(opts, {
method: method,
url: genDBUrl(host, '_all_docs' + paramStr),
body: body
}).then(function (res) {
if (opts.include_docs && opts.attachments && opts.binary) {
res.rows.forEach(readAttachmentsAsBlobOrBuffer);
}
callback(null, res);
}).catch(callback);
});
// Get a list of changes made to documents in the database given by host.
// TODO According to the README, there should be two other methods here,
// api.changes.addListener and api.changes.removeListener.
api._changes = function (opts) {
// We internally page the results of a changes request, this means
// if there is a large set of changes to be returned we can start
// processing them quicker instead of waiting on the entire
// set of changes to return and attempting to process them at once
var batchSize = 'batch_size' in opts ? opts.batch_size : CHANGES_BATCH_SIZE;
opts = (0, _clone2.default)(opts);
opts.timeout = opts.timeout || ajaxOpts.timeout || 30 * 1000;
// We give a 5 second buffer for CouchDB changes to respond with
// an ok timeout
var params = { timeout: opts.timeout - 5 * 1000 };
var limit = typeof opts.limit !== 'undefined' ? opts.limit : false;
var returnDocs;
if ('return_docs' in opts) {
returnDocs = opts.return_docs;
} else if ('returnDocs' in opts) {
// TODO: Remove 'returnDocs' in favor of 'return_docs' in a future release
returnDocs = opts.returnDocs;
} else {
returnDocs = true;
}
//
var leftToFetch = limit;
if (opts.style) {
params.style = opts.style;
}
if (opts.include_docs || opts.filter && typeof opts.filter === 'function') {
params.include_docs = true;
}
if (opts.attachments) {
params.attachments = true;
}
if (opts.continuous) {
params.feed = 'longpoll';
}
if (opts.conflicts) {
params.conflicts = true;
}
if (opts.descending) {
params.descending = true;
}
if ('heartbeat' in opts) {
// If the heartbeat value is false, it disables the default heartbeat
if (opts.heartbeat) {
params.heartbeat = opts.heartbeat;
}
} else {
// Default heartbeat to 10 seconds
params.heartbeat = 10000;
}
if (opts.filter && typeof opts.filter === 'string') {
params.filter = opts.filter;
if (opts.filter === '_view' && opts.view && typeof opts.view === 'string') {
params.view = opts.view;
}
}
// If opts.query_params exists, pass it through to the changes request.
// These parameters may be used by the filter on the source database.
if (opts.query_params && typeof opts.query_params === 'object') {
for (var param_name in opts.query_params) {
/* istanbul ignore else */
Eif (opts.query_params.hasOwnProperty(param_name)) {
params[param_name] = opts.query_params[param_name];
}
}
}
var method = 'GET';
var body;
if (opts.doc_ids) {
// set this automagically for the user; it's annoying that couchdb
// requires both a "filter" and a "doc_ids" param.
params.filter = '_doc_ids';
var docIdsJson = JSON.stringify(opts.doc_ids);
if (docIdsJson.length < MAX_URL_LENGTH) {
params.doc_ids = docIdsJson;
} else {
// anything greater than ~2000 is unsafe for gets, so
// use POST instead
method = 'POST';
body = { doc_ids: opts.doc_ids };
}
}
var xhr;
var lastFetchedSeq;
// Get all the changes starting wtih the one immediately after the
// sequence number given by since.
var fetch = function (since, callback) {
if (opts.aborted) {
return;
}
params.since = since;
// "since" can be any kind of json object in Coudant/CouchDB 2.x
/* istanbul ignore next */
Iif (typeof params.since === "object") {
params.since = JSON.stringify(params.since);
}
if (opts.descending) {
if (limit) {
params.limit = leftToFetch;
}
} else {
params.limit = !limit || leftToFetch > batchSize ? batchSize : leftToFetch;
}
// Set the options for the ajax call
var xhrOpts = {
method: method,
url: genDBUrl(host, '_changes' + paramsToStr(params)),
// _changes can take a long time to generate, especially when filtered
timeout: opts.timeout,
body: body
};
lastFetchedSeq = since;
/* istanbul ignore if */
Iif (opts.aborted) {
return;
}
// Get the changes
setup().then(function () {
xhr = ajax(opts, xhrOpts, callback);
}).catch(callback);
};
// If opts.since exists, get all the changes from the sequence
// number given by opts.since. Otherwise, get all the changes
// from the sequence number 0.
var results = { results: [] };
var fetched = function (err, res) {
if (opts.aborted) {
return;
}
var raw_results_length = 0;
// If the result of the ajax call (res) contains changes (res.results)
if (res && res.results) {
raw_results_length = res.results.length;
results.last_seq = res.last_seq;
// For each change
var req = {};
req.query = opts.query_params;
res.results = res.results.filter(function (c) {
leftToFetch--;
var ret = (0, _filterChange2.default)(opts)(c);
if (ret) {
if (opts.include_docs && opts.attachments && opts.binary) {
readAttachmentsAsBlobOrBuffer(c);
}
if (returnDocs) {
results.results.push(c);
}
opts.onChange(c);
}
return ret;
});
} else if (err) {
// In case of an error, stop listening for changes and call
// opts.complete
opts.aborted = true;
opts.complete(err);
return;
}
// The changes feed may have timed out with no results
// if so reuse last update sequence
if (res && res.last_seq) {
lastFetchedSeq = res.last_seq;
}
var finished = limit && leftToFetch <= 0 || res && raw_results_length < batchSize || opts.descending;
if (opts.continuous && !(limit && leftToFetch <= 0) || !finished) {
// Queue a call to fetch again with the newest sequence number
setTimeout(function () {
fetch(lastFetchedSeq, fetched);
}, 0);
} else {
// We're done, call the callback
opts.complete(null, results);
}
};
fetch(opts.since || 0, fetched);
// Return a method to cancel this method from processing any more
return {
cancel: function () {
opts.aborted = true;
if (xhr) {
xhr.abort();
}
}
};
};
// Given a set of document/revision IDs (given by req), tets the subset of
// those that do NOT correspond to revisions stored in the database.
// See http://wiki.apache.org/couchdb/HttpPostRevsDiff
api.revsDiff = adapterFun('revsDiff', function (req, opts, callback) {
// If no options were given, set the callback to be the second parameter
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
// Get the missing document/revision IDs
ajax(opts, {
method: 'POST',
url: genDBUrl(host, '_revs_diff'),
body: req
}, callback);
});
api._close = function (callback) {
callback();
};
api._destroy = function (options, callback) {
ajax(options, {
url: genDBUrl(host, ''),
method: 'DELETE'
}, function (err, resp) {
if (err && err.status && err.status !== 404) {
return callback(err);
}
api.emit('destroyed');
api.constructor.emit('destroyed', opts.name);
callback(null, resp);
});
};
}
// HttpPouch is a valid adapter.
HttpPouch.valid = function () {
return true;
};
exports.default = HttpPouch;
module.exports = exports['default']; |