-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclerk.js
1317 lines (1148 loc) · 38.6 KB
/
clerk.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
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
"use strict";
/*!
clerk - CouchDB client for node and the browser.
Copyright 2012-2015 Michael Phan-Ba
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Module dependencies.
var request = require("superagent");
/**
* Copy properties from sources to target.
*
* @param {Object} target The target object.
* @param {...Object} sources The source object.
* @return {Object} The target object.
* @private
*/
var extend = function (target /* ...sources */) {
var source, key, i = 1;
while (source = arguments[i++]) {
for (key in source) target[key] = source[key];
}
return target;
};
/**
* Stringify value.
*
* @param {Object} that That value to stringify.
* @return {String} The stringifyed value.
* @private
*/
var asString = function (that) {
return Object.prototype.toString.call(that);
};
/**
* Check if value is a string.
*
* @param {Object} that That value to check.
* @return {Boolean} `true` if string, `false` otherwise.
* @private
*/
var isString = function (that) {
return asString(that) == "[object String]";
};
/**
* Check if value is an object.
*
* @param {Object} that That value to check.
* @return {Boolean} `true` if object, `false` otherwise.
* @private
*/
var isObject = function (that) {
return asString(that) == "[object Object]";
};
/**
* Check if value is an array.
*
* @param {Object} that That value to check.
* @return {Boolean} `true` if array, `false` otherwise.
* @private
*/
var isArray = function (that) {
return asString(that) == "[object Array]";
};
/**
* Check if value is a function.
*
* @param {Object} that That value to check.
* @return {Boolean} `true` if function, `false` otherwise.
* @private
*/
var isFunction = function (that) {
return asString(that) == "[object Function]";
};
/**
* Clerk library entry point.
*
* @param {String} uri CouchDB server URI.
* @return {Client|DB} If a URI path is given, returns a `DB`, otherwise
* returns a `Client`.
* @see {@link http://docs.couchdb.org|CouchDB Documentation}
* @see {@link http://guide.couchdb.org/|CouchDB Guide}
* @see {@link http://wiki.apache.org/couchdb/|CouchDB Wiki}
*/
function clerk (uri) {
return clerk.make(uri);
};
/**
* Promise implementation.
* @type {Promise}
*/
clerk.Promise = typeof Promise !== "undefined" && Promise;
/**
* Library version.
* @type {String}
*/
clerk.version = "0.8.2";
/**
* Default host.
* @type {String}
*/
clerk.defaultHost = "http://127.0.0.1:5984";
/**
* Create single CouchDB client.
*
* @param {String} uri Fully qualified URI.
* @return {Client|DB} If `uri` has a path, the last segment of the
* path is used as the database name and a `DB` instance is
* returned. Otherwise, a `Client` instance is returned.
*/
clerk.make = function (uri) {
if (!uri) return new Client(this.defaultHost);
uri = clerk._parseURI(uri);
var db = /\/*([^\/]+)\/*$/.exec(uri.path);
if (db) {
uri.path = uri.path.substr(0, db.index);
db = db[1] && decodeURIComponent(db[1]);
}
// weird way of doing it, but it's more efficient...
if (uri.auth) uri.auth = 'Basic ' + clerk.btoa(uri.auth);
var client = new clerk.Client(uri.base + uri.path, uri.auth);
return db ? client.db(db) : client;
};
/**
* Base64-encode a string.
*
* @param {String} str
* @return {String}
*/
clerk.btoa = typeof Buffer != "undefined" ? function (str) {
return new Buffer(str).toString("base64");
} : function (str) {
return btoa(str);
};
/**
* Parse URI.
*
* The URI is normalized by removing extra `//` in the path.
*
* @param {String} uri Fully qualified URI.
* @return {String} The normalized URI.
* @private
*/
clerk._parseURI = function (uri) {
var match;
if (uri) {
if (match = /^(https?:\/\/)(?:([^\/@]+)@)?([^\/]+)(.*)\/*$/.exec(uri)) {
return {
base: match[1] + match[3].replace(/\/+/g, "\/"),
path: match[4],
auth: match[2] && decodeURIComponent(match[2])
};
}
}
return { base: uri || "", path: "" };
};
/**
* Base prototype for `Client` and `DB`.
* Encapsulates HTTP methods, JSON handling, and response coersion.
*
* @constructor
* @memberof clerk
*/
function Base () {};
/**
* Service request and parse JSON response.
*
* @param {String} [method=GET] HTTP method.
* @param {String} [path=this.uri] HTTP URI.
* @param {Object} [query] HTTP query options.
* @param {Object} [body] HTTP body.
* @param {Object} [headers] HTTP headers.
* @param {handler} [callback] Callback function.
* @return {Promise}
*/
Base.prototype.request = function (/* [method], [path], [query], [body], [headers], [callback] */) {
var args = [].slice.call(arguments);
var callback = isFunction (args[args.length - 1]) && args.pop();
return this._request({
method: args[0],
path: args[1],
query: args[2],
data: args[3],
headers: args[4],
fn: callback
});
};
/**
* Internal service request and parse JSON response handler.
*
* @param {String} options
* @param {String} method HTTP method.
* @param {String} path HTTP URI.
* @param {Object} query HTTP query options.
* @param {Object} data HTTP body data.
* @param {Object} headers HTTP headers.
* @param {handler} [callback] Callback function.
* @private
*/
Base.prototype._request = function (options) {
var self = this;
if (options.method == null) options.method = "GET";
if (options.headers == null) options.headers = {};
if (options.auth == null) options.auth = this.auth;
options.path = options.path ? "/" + options.path : "";
// set default headers
if (options.headers["Content-Type"] == null) {
options.headers["Content-Type"] = "application/json";
}
if (options.headers["Accept"] == null) {
options.headers["Accept"] = "application/json";
}
if (this.auth && options.headers["Authorization"] == null) {
options.headers["Authorization"] = this.auth;
}
options.uri = this.uri + options.path;
options.body = options.data && JSON.stringify(options.data,
/^\/_design/.test(options.path) && this._replacer
) || "";
// create promise if no callback given
var promise, req;
if (!options.fn && clerk.Promise) {
promise = new clerk.Promise(function (resolve, reject) {
options.fn = function (err, data, status, headers, res) {
if (err) {
err.body = data;
err.status = status;
err.headers = headers;
err.res = res;
reject(err);
} else {
if (isObject(data) && Object.defineProperties) {
Object.defineProperties(data, {
_status: { value: status },
_headers: { value: headers },
_response: { value: res },
});
}
resolve(data);
};
};
});
req = send();
promise.request = req;
promise.abort = function () {
req.abort();
options.fn(new Error("abort"));
return promise;
};
return promise;
}
send();
function send () {
// apply response transforms
var g = options._;
var fn = options.fn;
if (fn) {
options.fn = g ? function () {
fn.apply(self, g.apply(self, arguments) || arguments);
} : fn;
}
return self._do(options);
}
};
/**
* Provider for servicing requests and parsing JSON responses.
*
* @param {String} options
* @param {String} method HTTP method.
* @param {String} uri HTTP URI.
* @param {Object} query HTTP query options.
* @param {Object} body HTTP body.
* @param {Object} headers HTTP headers.
* @param {Object} auth HTTP authentication.
* @param {handler} [callback] Callback function.
* @private
*/
Base.prototype._do = function (options) {
var self = this;
var key, value;
var fn = options.fn;
// create request
var req = request(options.method, options.uri);
// query string
if (options.query) {
// ensure query Array values are JSON encoded
for (key in options.query) {
if (isObject(value = options.query[key])) {
options.query[key] = JSON.stringify(value);
}
}
// set query on request
req.query(options.query);
}
// set headers
if (options.headers) {
req.set(options.headers);
// if authenticating
if (req.withCredentials && options.headers["Authorization"] != null) {
req.withCredentials();
}
}
// send body
if (options.body) req.send(options.body);
// send request
req.end(function (err, res) {
var data;
if (!err) {
if (!(data = res.body)) { data = res.text; }
else if (data.error) err = self._error(data);
else data = self._response(data);
}
if (err && fn) {
var response = res || {};
return fn(err, data, response.status, response.header, res);
}
res.data = data;
if (fn) fn(err || null, data, res.status, res.header, res);
});
return req;
};
/**
* Coerce response to normalize access to `_id` and `_rev`.
*
* @param {Object} json The response JSON.
* @return The coerced JSON.
* @private
*/
Base.prototype._response = function (json) {
var data = json.rows || json.results || json.uuids || isArray(json) && json;
var meta = this._meta;
var i = 0, len, item;
if (data) {
extend(data, json).json = json;
for (len = data.length; i < len; i++) {
item = data[i] = meta(data[i]);
if (item.doc) item.doc = meta(item.doc);
}
} else {
data = meta(json);
}
return data;
};
/**
* Make an error out of the response.
*
* @param {Object} json The response JSON.
* @return An `Error` object.
* @private
*/
Base.prototype._error = function (json) {
var err = new Error(json.reason);
err.code = json.error;
return extend(err, json);
};
/**
* JSON stringify functions. Used for encoding view documents to JSON.
*
* @param {String} key The key to stringify.
* @param {Object} val The value to stringify.
* @return {Object} The stringified function value or the value.
* @private
*/
Base.prototype._replacer = function (key, val) {
return isFunction (val) ? val.toString() : val;
};
/**
* Coerce documents with prototypical `_id` and `_rev`
* values.
*
* @param {Object} doc The document to coerce.
* @return {Object} The coerced document.
* @private
*/
Base.prototype._meta = function (doc) {
var hasId = !doc._id && doc.id;
var hasRev = !doc._rev && doc.rev;
var proto;
if (hasId || hasRev) {
proto = function (){};
doc = extend(new proto(), doc);
proto = proto.prototype;
if (hasId) proto._id = doc.id;
if (hasRev) proto._rev = doc.rev;
}
return doc;
};
/**
* Parse arguments.
*
* @param {Array} args The arguments.
* @param {Integer} [start] The index from which to start reading arguments.
* @param {Boolean} [withBody] Set to `true` if the request body is given as a
* parameter before HTTP query options.
* @param {Boolean} [notDoc] The request body is not a document.
* @return {Promise} A Promise, if no callback is provided, otherwise `null`.
* @private
*/
Base.prototype._ = function (args, start, withBody, notDoc) {
var self = this, doc, id, rev;
function request(method, path, options) {
if (!options) options = {};
return self._request({
method: method,
path: path || request.p,
query: options.q || request.q,
data: options.b || request.b,
headers: options.h || request.h,
fn: options.f || request.f,
_: options._ || request._
});
}
// [id], [doc], [query], [header], [callback]
args = [].slice.call(args, start || 0);
request.f = isFunction(args[args.length - 1]) && args.pop();
request.p = isString(args[0]) && encodeURI(args.shift());
request.q = args[withBody ? 1 : 0] || {};
request.h = args[withBody ? 2 : 1] || {};
if (withBody) {
doc = request.b = args[0];
if (!notDoc) {
if (id = request.p || doc._id || doc.id) request.p = id;
if (rev = request.q.rev || doc._rev || doc.rev) request.q.rev = rev;
}
}
return request;
};
/**
* Clerk CouchDB client.
*
* @param {String} uri Fully qualified URI.
* @param {String} [auth] Authentication header value.
* @constructor
* @memberof clerk
* @see {@link http://wiki.apache.org/couchdb/Complete_HTTP_API_Reference|CouchDB Wiki}
*/
function Client (uri, auth) {
this.uri = uri;
this._db = {};
this.auth = auth;
};
Client.prototype = new Base();
/**
* Select database to manipulate.
*
* @param {String} name DB name.
* @return {DB} DB object.
*/
Client.prototype.db = function (name) {
var db = this._db;
return db[name] || (db[name] = new DB(this, name, this.auth));
};
/**
* List all databases.
*
* @param {Object} [query] HTTP query options.
* @param {Object} [headers] HTTP headers.
* @param {handler} [callback] Callback function.
* @return {Promise} A Promise, if no callback is provided,
* otherwise `null`.
* @see {@link http://wiki.apache.org/couchdb/HttpGetAllDbs|CouchDB Wiki}
*/
Client.prototype.dbs = function (/* [query], [headers], [callback] */) {
return this._(arguments)("GET", "_all_dbs");
};
/**
* Get UUIDs.
*
* @param {Integer} [count=1] Number of UUIDs to get.
* @param {Object} [query] HTTP query options.
* @param {Object} [headers] HTTP headers.
* @param {handler} [callback] Callback function.
* @return {Promise} A Promise, if no callback is provided,
* otherwise `null`.
* @see {@link http://wiki.apache.org/couchdb/HttpGetUuids|CouchDB Wiki}
*/
Client.prototype.uuids = function (count /* [query], [headers], [callback] */) {
var request = this._(arguments, +count == count ? 1 : 0);
if (count > 1) request.q.count = count;
return request("GET", "_uuids");
};
/**
* Get server information.
*
* @param {Object} [query] HTTP query options.
* @param {Object} [headers] HTTP headers.
* @param {handler} [callback] Callback function.
* @return {Promise} A Promise, if no callback is provided,
* otherwise `null`.
* @see {@link http://wiki.apache.org/couchdb/HttpGetRoot|CouchDB Wiki}
*/
Client.prototype.info = function (/* [query], [headers], [callback] */) {
return this._(arguments)("GET");
};
/**
* Get server stats.
*
* @param {Object} [query] HTTP query options.
* @param {Object} [headers] HTTP headers.
* @param {handler} [callback] Callback function.
* @return {Promise} A Promise, if no callback is provided,
* otherwise `null`.
* @see {@link http://wiki.apache.org/couchdb/HttpGetLog|CouchDB Wiki}
*/
Client.prototype.stats = function (/* [query], [headers], [callback] */) {
return this._(arguments)("GET", "_stats");
};
/**
* Get tail of the server log file.
*
* @param {Object} [query] Query parameters.
* @param {Integer} [query.bytes] Number of bytes to read.
* @param {Integer} [query.offset] Number of bytes from the end of
* log file to start reading.
* @param {Object} [headers] HTTP headers.
* @param {handler} [callback] Callback function.
* @return {Promise} A Promise, if no callback is provided,
* otherwise `null`.
* @see {@link http://wiki.apache.org/couchdb/HttpGetLog|CouchDB Wiki}
*/
Client.prototype.log = function (/* [query], [headers], [callback] */) {
return this._(arguments)("GET", "_log");
};
/**
* List running tasks.
*
* @param {Object} [query] HTTP query options.
* @param {Object} [headers] HTTP headers.
* @param {handler} [callback] Callback function.
* @return {Promise} A Promise, if no callback is provided,
* otherwise `null`.
* @see {@link http://wiki.apache.org/couchdb/HttpGetActiveTasks|CouchDB Wiki}
*/
Client.prototype.tasks = function (/* [query], [headers], [callback] */) {
return this._(arguments)("GET", "_active_tasks");
};
/**
* Get or set configuration values.
*
* @param {String} [key] Configuration section or key.
* @param {String} [value] Configuration value.
* @param {Object} [query] HTTP query options.
* @param {Object} [headers] HTTP headers.
* @param {handler} [callback] Callback function.
* @return {Promise} A Promise, if no callback is provided,
* otherwise `null`.
*/
Client.prototype.config = function (/* [key], [value], [query], [headers], [callback] */) {
var args = [].slice.call(arguments);
var key = isString(args[0]) && args.shift() || "";
var value = isString(args[0]) && args.shift();
var method = isString(value) ? "PUT" : "GET";
return this._(args)(method, "_config/" + key, { b: value });
};
/**
* Replicate databases.
*
* @param {Object} options Options.
* @param {String} options.source Source database URL or local name.
* @param {String} options.target Target database URL or local name.
* @param {Boolean} [options.cancel] Set to `true` to cancel replication.
* @param {Boolean} [options.continuous] Set to `true` for continuous
* replication.
* @param {Boolean} [options.create_target] Set to `true` to create the
* target database.
* @param {String} [options.filter] Filter name for filtered replication.
* Example: "mydesign/myfilter".
* @param {Object} [options.query] Query parameters for filter.
* @param {String[]} [options.doc_ids] Document IDs to replicate.
* @param {String} [options.proxy] Proxy through which to replicate.
* @param {Object} [query] HTTP query options.
* @param {Object} [headers] HTTP headers.
* @param {handler} [callback] Callback function.
* @return {Promise} A Promise, if no callback is provided,
* otherwise `null`.
* @see {@link http://wiki.apache.org/couchdb/Replication|CouchDB Wiki}
*/
Client.prototype.replicate = function (options /* [query], [headers], [callback] */) {
return this._(arguments, 1)("POST", "_replicate", { b: options });
};
/**
* Methods for CouchDB database.
*
* @param {Client} client Clerk client.
* @param {String} name DB name.
* @param {String} [auth] Authentication header value.
* @constructor
* @memberof clerk
* @return This object for chaining.
*/
function DB (client, name, auth) {
this.client = client;
this.name = name;
this.uri = client.uri + "/" + encodeURIComponent(name);
this.auth = auth;
};
DB.prototype = new Base();
/**
* Create database.
*
* @param {Object} [query] HTTP query options.
* @param {Object} [headers] HTTP headers.
* @param {handler} [callback] Callback function.
* @return {Promise} A Promise, if no callback is provided,
* otherwise `null`.
*/
DB.prototype.create = function (/* [query], [headers], [callback] */) {
return this._(arguments)("PUT");
};
/**
* Destroy database.
*
* @param {Object} [query] HTTP query options.
* @param {Object} [headers] HTTP headers.
* @param {handler} [callback] Callback function.
* @return {Promise} A Promise, if no callback is provided,
* otherwise `null`.
*/
DB.prototype.destroy = function (/* [query], [headers], [callback] */) {
return this._(arguments)("DELETE");
};
/**
* Get database info.
*
* @param {Object} [query] HTTP query options.
* @param {Object} [headers] HTTP headers.
* @param {handler} [callback] Callback function.
* @return {Promise} A Promise, if no callback is provided,
* otherwise `null`.
*/
DB.prototype.info = function (/* [query], [headers], callback */) {
return this._(arguments)("GET");
};
/**
* Check if database exists.
*
* @param {Object} [query] HTTP query options.
* @param {Object} [headers] HTTP headers.
* @param {handler} [callback] Callback function.
* @return {Promise} A Promise, if no callback is provided,
* otherwise `null`.
*/
DB.prototype.exists = function (/* [query], [headers], callback */) {
var request = this._(arguments);
request._ = function (err, body, status, headers, req) {
if (status === 404) err = null;
return [err, status === 200, status, headers, req];
};
return request("HEAD");
};
/**
* Fetch document.
*
* Set `rev` in `query`.
*
* @param {String} id Document ID.
* @param {Object} [query] HTTP query options.
* @param {Boolean} [query.revs] Fetch list of revisions.
* @param {Boolean} [query.revs_info] Fetch detailed revision information.
* @param {Object} [headers] HTTP headers.
* @param {handler} [callback] Callback function.
* @return {Promise} A Promise, if no callback is provided,
* otherwise `null`.
* @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#GET|CouchDB Wiki}
*/
DB.prototype.get = function (/* [id], [query], [headers], [callback] */) {
return this._(arguments)("GET");
};
/**
* Get document metadata.
*
* @param {String} id Document ID.
* @param {Object} [query] HTTP query options.
* @param {Object} [headers] HTTP headers.
* @param {handler} [callback] Callback function.
* @return {Promise} A Promise, if no callback is provided,
* otherwise `null`.
* @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#HEAD|CouchDB Wiki}
*/
DB.prototype.head = function (/* [id], [query], [headers], callback */) {
var self = this;
var request = self._(arguments);
request._ = function (err, body, status, headers, res) {
return [err, err ? null : {
_id: request.p,
_rev: headers.etag && JSON.parse(headers.etag),
contentType: headers["content-type"],
contentLength: headers["content-length"]
}, status, headers, res];
};
return request("HEAD");
};
/**
* Post document(s) to database.
*
* If documents have no ID, a document ID will be automatically generated
* on the server. Attachments are not currently supported.
*
* @param {Object|Object[]} doc Document or array of documents.
* @param {String} [doc._id] Document ID. If set, uses given document ID.
* @param {String} [doc._rev] Document revision. If set, allows update to
* existing document.
* @param {Object} [doc._attachments] Attachments. If given, must be a
* map of filenames to attachment properties.
* @param {String} [doc._attachments[filename]] Attachment filename, as
* hash key.
* @param {String} [doc._attachments[filename].contentType] Attachment
* MIME content type.
* @param {String|Object} [doc._attachments[filename].data] Attachment
* data. Will be Base64 encoded.
* @param {Object} [query] HTTP query options.
* @param {Boolean} [query.batch] Allow server to write document in
* batch mode. Documents will not be written to disk immediately,
* increasing the chances of write failure.
* @param {Boolean} [query.all_or_nothing] For batch updating of
* documents, use all-or-nothing semantics.
* @param {Object} [headers] HTTP headers.
* @param {handler} [callback] Callback function.
* @return {Promise} A Promise, if no callback is provided,
* otherwise `null`.
* @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#POST|CouchDB Wiki}
* @see {@link http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API|CouchDB Wiki}
*/
DB.prototype.post = function (docs /* [query], [headers], [callback] */) {
var request = this._(arguments, 1);
if (isArray(docs)) {
request.p = "_bulk_docs";
request.b = extend({ docs: docs }, request.q);
request.q = null
} else {
request.b = docs;
}
return request("POST");
};
/**
* Put document in database.
*
* @param {Object} doc Document data. Requires `_id` and `_rev`.
* @param {String} [options] Options.
* @param {Object} [query] HTTP query options.
* @param {Object} [headers] HTTP headers.
* @param {handler} [callback] Callback function.
* @return {Promise} A Promise, if no callback is provided,
* otherwise `null`.
* @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#PUT|CouchDB Wiki}
*/
DB.prototype.put = function (/* [id], [doc], [query], [headers], [callback] */) {
var request = this._(arguments, 0, 1);
// prevent acidentally creating database
if (!request.p) request.p = request.b._id || request.b.id;
if (!request.p) throw new Error("missing id");
return request("PUT");
};
/**
* Delete document(s).
*
* @param {Object|Object[]} docs Document or array of documents.
* @param {Object} [query] HTTP query options.
* @param {Object} [headers] HTTP headers.
* @param {handler} [callback] Callback function.
* @return {Promise} A Promise, if no callback is provided,
* otherwise `null`.
* @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#DELETE|CouchDB Wiki}
* @see {@link http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API|CouchDB Wiki}
*/
DB.prototype.del = function (docs /* [query], [headers], [callback] */) {
if (isArray(docs)) {
var i = 0, len = docs.length, doc;
for (; i < len; i++) {
doc = docs[i], docs[i] = {
_id: doc._id || doc.id,
_rev: doc._rev || doc.rev,
_deleted: true
};
}
return this.post.apply(this, arguments);
} else {
var request = this._(arguments, 0, 1);
// prevent acidentally deleting database
if (!request.p) throw new Error("missing id");
return request("DELETE");
}
};
/**
* Copy document.
*
* @param {Object} source Source document.
* @param {String} source.id Source document ID.
* @param {String} [source.rev] Source document revision.
* @param {String} [source._id] Source document ID. Alternate key for
* `source.id`.
* @param {String} [source._rev] Source document revision. Alternate key
* for `source.id`.
* @param {Object} target Target document.
* @param {String} target.id Target document ID.
* @param {String} [target.rev] Target document revision.
* @param {String} [target._id] Target document ID. Alternate key for
* `target.id`.
* @param {String} [target._rev] Target document revision. Alternate key
* for `target.id`.
* @param {Object} [query] HTTP query options.
* @param {Object} [headers] HTTP headers.
* @param {handler} [callback] Callback function.
* @return {Promise} A Promise, if no callback is provided,
* otherwise `null`.
* @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#COPY|CouchDB Wiki}
*/
DB.prototype.copy = function (source, target /* [query], [headers], [callback] */) {
var request = this._(arguments, 2);
var sourcePath = encodeURIComponent(source.id || source._id || source);
var targetPath = encodeURIComponent(target.id || target._id || target);
var sourceRev = source.rev || source._rev;
var targetRev = target.rev || target._rev;
if (sourceRev) request.q.rev = sourceRev;
if (targetRev) targetPath += "?rev=" + encodeURIComponent(targetRev);
request.h.Destination = targetPath;
return request("COPY", sourcePath);
};
/**
* Query all documents by ID.
*
* @param {Object} [query] HTTP query options.
* @param {JSON} [query.startkey] Start returning results from this
* document ID.
* @param {JSON} [query.endkey] Stop returning results at this document
* ID.
* @param {Integer} [query.limit] Limit number of results returned.
* @param {Boolean} [query.descending=false] Lookup results in reverse
* order by key, returning documents in descending order by key.
* @param {Integer} [query.skip] Skip this many records before
* returning results.
* @param {Boolean} [query.include_docs=false] Include document source for
* each result.
* @param {Boolean} [query.include_end=true] Include `query.endkey`
* in results.
* @param {Boolean} [query.update_seq=false] Include sequence value
* of the database corresponding to the view.
* @param {Object} [headers] HTTP headers.
* @param {handler} [callback] Callback function.
* @return {Promise} A Promise, if no callback is provided,
* otherwise `null`.
* @see {@link http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API|CouchDB Wiki}
*/
DB.prototype.all = function (/* [query], [headers], [callback] */) {
var request = this._(arguments);
var body = this._viewOptions(request.q);
return request(body ? "POST" : "GET", "_all_docs", { b: body });
};
/**
* Query a view.
*
* @param {String|Object} view View name (e.g. mydesign/myview) or
* temporary view definition. Using a temporary view is strongly not
* recommended for production use.
* @param {Object} [query] HTTP query options.
* @param {JSON} [query.key] Key to lookup.
* @param {JSON} [query.startkey] Start returning results from this key.
* @param {String} [query.startkey_docid] Start returning results
* from this document ID. Allows pagination with duplicate keys.
* @param {JSON} [query.endkey] Stop returning results at this key.