clerk 0.8.3 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/clerk.js DELETED
@@ -1,1317 +0,0 @@
1
- "use strict";
2
-
3
- /*!
4
-
5
- clerk - CouchDB client for node and the browser.
6
- Copyright 2012-2015 Michael Phan-Ba
7
-
8
- Licensed under the Apache License, Version 2.0 (the "License");
9
- you may not use this file except in compliance with the License.
10
- You may obtain a copy of the License at
11
-
12
- http://www.apache.org/licenses/LICENSE-2.0
13
-
14
- Unless required by applicable law or agreed to in writing, software
15
- distributed under the License is distributed on an "AS IS" BASIS,
16
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
- See the License for the specific language governing permissions and
18
- limitations under the License.
19
-
20
- */
21
-
22
- // Module dependencies.
23
- var request = require("superagent");
24
-
25
- /**
26
- * Copy properties from sources to target.
27
- *
28
- * @param {Object} target The target object.
29
- * @param {...Object} sources The source object.
30
- * @return {Object} The target object.
31
- * @private
32
- */
33
-
34
- var extend = function (target /* ...sources */) {
35
- var source, key, i = 1;
36
- while (source = arguments[i++]) {
37
- for (key in source) target[key] = source[key];
38
- }
39
- return target;
40
- };
41
-
42
- /**
43
- * Stringify value.
44
- *
45
- * @param {Object} that That value to stringify.
46
- * @return {String} The stringifyed value.
47
- * @private
48
- */
49
-
50
- var asString = function (that) {
51
- return Object.prototype.toString.call(that);
52
- };
53
-
54
- /**
55
- * Check if value is a string.
56
- *
57
- * @param {Object} that That value to check.
58
- * @return {Boolean} `true` if string, `false` otherwise.
59
- * @private
60
- */
61
-
62
- var isString = function (that) {
63
- return asString(that) == "[object String]";
64
- };
65
-
66
- /**
67
- * Check if value is an object.
68
- *
69
- * @param {Object} that That value to check.
70
- * @return {Boolean} `true` if object, `false` otherwise.
71
- * @private
72
- */
73
-
74
- var isObject = function (that) {
75
- return asString(that) == "[object Object]";
76
- };
77
-
78
- /**
79
- * Check if value is an array.
80
- *
81
- * @param {Object} that That value to check.
82
- * @return {Boolean} `true` if array, `false` otherwise.
83
- * @private
84
- */
85
-
86
- var isArray = function (that) {
87
- return asString(that) == "[object Array]";
88
- };
89
-
90
- /**
91
- * Check if value is a function.
92
- *
93
- * @param {Object} that That value to check.
94
- * @return {Boolean} `true` if function, `false` otherwise.
95
- * @private
96
- */
97
-
98
- var isFunction = function (that) {
99
- return asString(that) == "[object Function]";
100
- };
101
-
102
- /**
103
- * Clerk library entry point.
104
- *
105
- * @param {String} uri CouchDB server URI.
106
- * @return {Client|DB} If a URI path is given, returns a `DB`, otherwise
107
- * returns a `Client`.
108
- * @see {@link http://docs.couchdb.org|CouchDB Documentation}
109
- * @see {@link http://guide.couchdb.org/|CouchDB Guide}
110
- * @see {@link http://wiki.apache.org/couchdb/|CouchDB Wiki}
111
- */
112
-
113
- function clerk (uri) {
114
- return clerk.make(uri);
115
- };
116
-
117
- /**
118
- * Promise implementation.
119
- * @type {Promise}
120
- */
121
-
122
- clerk.Promise = typeof Promise !== "undefined" && Promise;
123
-
124
- /**
125
- * Library version.
126
- * @type {String}
127
- */
128
-
129
- clerk.version = "0.8.2";
130
-
131
- /**
132
- * Default host.
133
- * @type {String}
134
- */
135
-
136
- clerk.defaultHost = "http://127.0.0.1:5984";
137
-
138
- /**
139
- * Create single CouchDB client.
140
- *
141
- * @param {String} uri Fully qualified URI.
142
- * @return {Client|DB} If `uri` has a path, the last segment of the
143
- * path is used as the database name and a `DB` instance is
144
- * returned. Otherwise, a `Client` instance is returned.
145
- */
146
-
147
- clerk.make = function (uri) {
148
- if (!uri) return new Client(this.defaultHost);
149
-
150
- uri = clerk._parseURI(uri);
151
-
152
- var db = /\/*([^\/]+)\/*$/.exec(uri.path);
153
- if (db) {
154
- uri.path = uri.path.substr(0, db.index);
155
- db = db[1] && decodeURIComponent(db[1]);
156
- }
157
-
158
- // weird way of doing it, but it's more efficient...
159
- if (uri.auth) uri.auth = 'Basic ' + clerk.btoa(uri.auth);
160
-
161
- var client = new clerk.Client(uri.base + uri.path, uri.auth);
162
- return db ? client.db(db) : client;
163
- };
164
-
165
- /**
166
- * Base64-encode a string.
167
- *
168
- * @param {String} str
169
- * @return {String}
170
- */
171
-
172
- clerk.btoa = typeof Buffer != "undefined" ? function (str) {
173
- return new Buffer(str).toString("base64");
174
- } : function (str) {
175
- return btoa(str);
176
- };
177
-
178
- /**
179
- * Parse URI.
180
- *
181
- * The URI is normalized by removing extra `//` in the path.
182
- *
183
- * @param {String} uri Fully qualified URI.
184
- * @return {String} The normalized URI.
185
- * @private
186
- */
187
-
188
- clerk._parseURI = function (uri) {
189
- var match;
190
-
191
- if (uri) {
192
- if (match = /^(https?:\/\/)(?:([^\/@]+)@)?([^\/]+)(.*)\/*$/.exec(uri)) {
193
- return {
194
- base: match[1] + match[3].replace(/\/+/g, "\/"),
195
- path: match[4],
196
- auth: match[2] && decodeURIComponent(match[2])
197
- };
198
- }
199
- }
200
-
201
- return { base: uri || "", path: "" };
202
- };
203
-
204
- /**
205
- * Base prototype for `Client` and `DB`.
206
- * Encapsulates HTTP methods, JSON handling, and response coersion.
207
- *
208
- * @constructor
209
- * @memberof clerk
210
- */
211
-
212
- function Base () {};
213
-
214
- /**
215
- * Service request and parse JSON response.
216
- *
217
- * @param {String} [method=GET] HTTP method.
218
- * @param {String} [path=this.uri] HTTP URI.
219
- * @param {Object} [query] HTTP query options.
220
- * @param {Object} [body] HTTP body.
221
- * @param {Object} [headers] HTTP headers.
222
- * @param {handler} [callback] Callback function.
223
- * @return {Promise}
224
- */
225
-
226
- Base.prototype.request = function (/* [method], [path], [query], [body], [headers], [callback] */) {
227
- var args = [].slice.call(arguments);
228
- var callback = isFunction (args[args.length - 1]) && args.pop();
229
-
230
- return this._request({
231
- method: args[0],
232
- path: args[1],
233
- query: args[2],
234
- data: args[3],
235
- headers: args[4],
236
- fn: callback
237
- });
238
- };
239
-
240
- /**
241
- * Internal service request and parse JSON response handler.
242
- *
243
- * @param {String} options
244
- * @param {String} method HTTP method.
245
- * @param {String} path HTTP URI.
246
- * @param {Object} query HTTP query options.
247
- * @param {Object} data HTTP body data.
248
- * @param {Object} headers HTTP headers.
249
- * @param {handler} [callback] Callback function.
250
- * @private
251
- */
252
-
253
- Base.prototype._request = function (options) {
254
- var self = this;
255
-
256
- if (options.method == null) options.method = "GET";
257
- if (options.headers == null) options.headers = {};
258
- if (options.auth == null) options.auth = this.auth;
259
-
260
- options.path = options.path ? "/" + options.path : "";
261
-
262
- // set default headers
263
- if (options.headers["Content-Type"] == null) {
264
- options.headers["Content-Type"] = "application/json";
265
- }
266
- if (options.headers["Accept"] == null) {
267
- options.headers["Accept"] = "application/json";
268
- }
269
- if (this.auth && options.headers["Authorization"] == null) {
270
- options.headers["Authorization"] = this.auth;
271
- }
272
-
273
- options.uri = this.uri + options.path;
274
- options.body = options.data && JSON.stringify(options.data,
275
- /^\/_design/.test(options.path) && this._replacer
276
- ) || "";
277
-
278
- // create promise if no callback given
279
- var promise, req;
280
- if (!options.fn && clerk.Promise) {
281
- promise = new clerk.Promise(function (resolve, reject) {
282
- options.fn = function (err, data, status, headers, res) {
283
- if (err) {
284
- err.body = data;
285
- err.status = status;
286
- err.headers = headers;
287
- err.res = res;
288
- reject(err);
289
- } else {
290
- if (isObject(data) && Object.defineProperties) {
291
- Object.defineProperties(data, {
292
- _status: { value: status },
293
- _headers: { value: headers },
294
- _response: { value: res },
295
- });
296
- }
297
- resolve(data);
298
- };
299
- };
300
- });
301
- req = send();
302
- promise.request = req;
303
- promise.abort = function () {
304
- req.abort();
305
- options.fn(new Error("abort"));
306
- return promise;
307
- };
308
- return promise;
309
- }
310
-
311
- send();
312
-
313
- function send () {
314
- // apply response transforms
315
- var g = options._;
316
- var fn = options.fn;
317
- if (fn) {
318
- options.fn = g ? function () {
319
- fn.apply(self, g.apply(self, arguments) || arguments);
320
- } : fn;
321
- }
322
- return self._do(options);
323
- }
324
- };
325
-
326
- /**
327
- * Provider for servicing requests and parsing JSON responses.
328
- *
329
- * @param {String} options
330
- * @param {String} method HTTP method.
331
- * @param {String} uri HTTP URI.
332
- * @param {Object} query HTTP query options.
333
- * @param {Object} body HTTP body.
334
- * @param {Object} headers HTTP headers.
335
- * @param {Object} auth HTTP authentication.
336
- * @param {handler} [callback] Callback function.
337
- * @private
338
- */
339
-
340
- Base.prototype._do = function (options) {
341
- var self = this;
342
- var key, value;
343
- var fn = options.fn;
344
-
345
- // create request
346
- var req = request(options.method, options.uri);
347
-
348
- // query string
349
- if (options.query) {
350
- // ensure query Array values are JSON encoded
351
- for (key in options.query) {
352
- if (isObject(value = options.query[key])) {
353
- options.query[key] = JSON.stringify(value);
354
- }
355
- }
356
- // set query on request
357
- req.query(options.query);
358
- }
359
-
360
- // set headers
361
- if (options.headers) {
362
- req.set(options.headers);
363
- // if authenticating
364
- if (req.withCredentials && options.headers["Authorization"] != null) {
365
- req.withCredentials();
366
- }
367
- }
368
-
369
- // send body
370
- if (options.body) req.send(options.body);
371
-
372
- // send request
373
- req.end(function (err, res) {
374
- var data;
375
-
376
- if (!err) {
377
- if (!(data = res.body)) { data = res.text; }
378
- else if (data.error) err = self._error(data);
379
- else data = self._response(data);
380
- }
381
-
382
- if (err && fn) {
383
- var response = res || {};
384
- return fn(err, data, response.status, response.header, res);
385
- }
386
-
387
- res.data = data;
388
- if (fn) fn(err || null, data, res.status, res.header, res);
389
- });
390
-
391
- return req;
392
- };
393
-
394
- /**
395
- * Coerce response to normalize access to `_id` and `_rev`.
396
- *
397
- * @param {Object} json The response JSON.
398
- * @return The coerced JSON.
399
- * @private
400
- */
401
-
402
- Base.prototype._response = function (json) {
403
- var data = json.rows || json.results || json.uuids || isArray(json) && json;
404
- var meta = this._meta;
405
- var i = 0, len, item;
406
-
407
- if (data) {
408
- extend(data, json).json = json;
409
- for (len = data.length; i < len; i++) {
410
- item = data[i] = meta(data[i]);
411
- if (item.doc) item.doc = meta(item.doc);
412
- }
413
- } else {
414
- data = meta(json);
415
- }
416
-
417
- return data;
418
- };
419
-
420
- /**
421
- * Make an error out of the response.
422
- *
423
- * @param {Object} json The response JSON.
424
- * @return An `Error` object.
425
- * @private
426
- */
427
-
428
- Base.prototype._error = function (json) {
429
- var err = new Error(json.reason);
430
- err.code = json.error;
431
- return extend(err, json);
432
- };
433
-
434
- /**
435
- * JSON stringify functions. Used for encoding view documents to JSON.
436
- *
437
- * @param {String} key The key to stringify.
438
- * @param {Object} val The value to stringify.
439
- * @return {Object} The stringified function value or the value.
440
- * @private
441
- */
442
-
443
- Base.prototype._replacer = function (key, val) {
444
- return isFunction (val) ? val.toString() : val;
445
- };
446
-
447
- /**
448
- * Coerce documents with prototypical `_id` and `_rev`
449
- * values.
450
- *
451
- * @param {Object} doc The document to coerce.
452
- * @return {Object} The coerced document.
453
- * @private
454
- */
455
-
456
- Base.prototype._meta = function (doc) {
457
- var hasId = !doc._id && doc.id;
458
- var hasRev = !doc._rev && doc.rev;
459
- var proto;
460
-
461
- if (hasId || hasRev) {
462
- proto = function (){};
463
- doc = extend(new proto(), doc);
464
- proto = proto.prototype;
465
- if (hasId) proto._id = doc.id;
466
- if (hasRev) proto._rev = doc.rev;
467
- }
468
-
469
- return doc;
470
- };
471
-
472
- /**
473
- * Parse arguments.
474
- *
475
- * @param {Array} args The arguments.
476
- * @param {Integer} [start] The index from which to start reading arguments.
477
- * @param {Boolean} [withBody] Set to `true` if the request body is given as a
478
- * parameter before HTTP query options.
479
- * @param {Boolean} [notDoc] The request body is not a document.
480
- * @return {Promise} A Promise, if no callback is provided, otherwise `null`.
481
- * @private
482
- */
483
-
484
- Base.prototype._ = function (args, start, withBody, notDoc) {
485
- var self = this, doc, id, rev;
486
-
487
- function request(method, path, options) {
488
- if (!options) options = {};
489
- return self._request({
490
- method: method,
491
- path: path || request.p,
492
- query: options.q || request.q,
493
- data: options.b || request.b,
494
- headers: options.h || request.h,
495
- fn: options.f || request.f,
496
- _: options._ || request._
497
- });
498
- }
499
-
500
- // [id], [doc], [query], [header], [callback]
501
- args = [].slice.call(args, start || 0);
502
-
503
- request.f = isFunction(args[args.length - 1]) && args.pop();
504
- request.p = isString(args[0]) && encodeURI(args.shift());
505
- request.q = args[withBody ? 1 : 0] || {};
506
- request.h = args[withBody ? 2 : 1] || {};
507
-
508
- if (withBody) {
509
- doc = request.b = args[0];
510
- if (!notDoc) {
511
- if (id = request.p || doc._id || doc.id) request.p = id;
512
- if (rev = request.q.rev || doc._rev || doc.rev) request.q.rev = rev;
513
- }
514
- }
515
-
516
- return request;
517
- };
518
-
519
- /**
520
- * Clerk CouchDB client.
521
- *
522
- * @param {String} uri Fully qualified URI.
523
- * @param {String} [auth] Authentication header value.
524
- * @constructor
525
- * @memberof clerk
526
- * @see {@link http://wiki.apache.org/couchdb/Complete_HTTP_API_Reference|CouchDB Wiki}
527
- */
528
-
529
- function Client (uri, auth) {
530
- this.uri = uri;
531
- this._db = {};
532
- this.auth = auth;
533
- };
534
-
535
- Client.prototype = new Base();
536
-
537
- /**
538
- * Select database to manipulate.
539
- *
540
- * @param {String} name DB name.
541
- * @return {DB} DB object.
542
- */
543
-
544
- Client.prototype.db = function (name) {
545
- var db = this._db;
546
- return db[name] || (db[name] = new DB(this, name, this.auth));
547
- };
548
-
549
- /**
550
- * List all databases.
551
- *
552
- * @param {Object} [query] HTTP query options.
553
- * @param {Object} [headers] HTTP headers.
554
- * @param {handler} [callback] Callback function.
555
- * @return {Promise} A Promise, if no callback is provided,
556
- * otherwise `null`.
557
- * @see {@link http://wiki.apache.org/couchdb/HttpGetAllDbs|CouchDB Wiki}
558
- */
559
-
560
- Client.prototype.dbs = function (/* [query], [headers], [callback] */) {
561
- return this._(arguments)("GET", "_all_dbs");
562
- };
563
-
564
- /**
565
- * Get UUIDs.
566
- *
567
- * @param {Integer} [count=1] Number of UUIDs to get.
568
- * @param {Object} [query] HTTP query options.
569
- * @param {Object} [headers] HTTP headers.
570
- * @param {handler} [callback] Callback function.
571
- * @return {Promise} A Promise, if no callback is provided,
572
- * otherwise `null`.
573
- * @see {@link http://wiki.apache.org/couchdb/HttpGetUuids|CouchDB Wiki}
574
- */
575
-
576
- Client.prototype.uuids = function (count /* [query], [headers], [callback] */) {
577
- var request = this._(arguments, +count == count ? 1 : 0);
578
- if (count > 1) request.q.count = count;
579
- return request("GET", "_uuids");
580
- };
581
-
582
- /**
583
- * Get server information.
584
- *
585
- * @param {Object} [query] HTTP query options.
586
- * @param {Object} [headers] HTTP headers.
587
- * @param {handler} [callback] Callback function.
588
- * @return {Promise} A Promise, if no callback is provided,
589
- * otherwise `null`.
590
- * @see {@link http://wiki.apache.org/couchdb/HttpGetRoot|CouchDB Wiki}
591
- */
592
-
593
- Client.prototype.info = function (/* [query], [headers], [callback] */) {
594
- return this._(arguments)("GET");
595
- };
596
-
597
- /**
598
- * Get server stats.
599
- *
600
- * @param {Object} [query] HTTP query options.
601
- * @param {Object} [headers] HTTP headers.
602
- * @param {handler} [callback] Callback function.
603
- * @return {Promise} A Promise, if no callback is provided,
604
- * otherwise `null`.
605
- * @see {@link http://wiki.apache.org/couchdb/HttpGetLog|CouchDB Wiki}
606
- */
607
-
608
- Client.prototype.stats = function (/* [query], [headers], [callback] */) {
609
- return this._(arguments)("GET", "_stats");
610
- };
611
-
612
- /**
613
- * Get tail of the server log file.
614
- *
615
- * @param {Object} [query] Query parameters.
616
- * @param {Integer} [query.bytes] Number of bytes to read.
617
- * @param {Integer} [query.offset] Number of bytes from the end of
618
- * log file to start reading.
619
- * @param {Object} [headers] HTTP headers.
620
- * @param {handler} [callback] Callback function.
621
- * @return {Promise} A Promise, if no callback is provided,
622
- * otherwise `null`.
623
- * @see {@link http://wiki.apache.org/couchdb/HttpGetLog|CouchDB Wiki}
624
- */
625
-
626
- Client.prototype.log = function (/* [query], [headers], [callback] */) {
627
- return this._(arguments)("GET", "_log");
628
- };
629
-
630
- /**
631
- * List running tasks.
632
- *
633
- * @param {Object} [query] HTTP query options.
634
- * @param {Object} [headers] HTTP headers.
635
- * @param {handler} [callback] Callback function.
636
- * @return {Promise} A Promise, if no callback is provided,
637
- * otherwise `null`.
638
- * @see {@link http://wiki.apache.org/couchdb/HttpGetActiveTasks|CouchDB Wiki}
639
- */
640
-
641
- Client.prototype.tasks = function (/* [query], [headers], [callback] */) {
642
- return this._(arguments)("GET", "_active_tasks");
643
- };
644
-
645
- /**
646
- * Get or set configuration values.
647
- *
648
- * @param {String} [key] Configuration section or key.
649
- * @param {String} [value] Configuration value.
650
- * @param {Object} [query] HTTP query options.
651
- * @param {Object} [headers] HTTP headers.
652
- * @param {handler} [callback] Callback function.
653
- * @return {Promise} A Promise, if no callback is provided,
654
- * otherwise `null`.
655
- */
656
-
657
- Client.prototype.config = function (/* [key], [value], [query], [headers], [callback] */) {
658
- var args = [].slice.call(arguments);
659
- var key = isString(args[0]) && args.shift() || "";
660
- var value = isString(args[0]) && args.shift();
661
- var method = isString(value) ? "PUT" : "GET";
662
- return this._(args)(method, "_config/" + key, { b: value });
663
- };
664
-
665
- /**
666
- * Replicate databases.
667
- *
668
- * @param {Object} options Options.
669
- * @param {String} options.source Source database URL or local name.
670
- * @param {String} options.target Target database URL or local name.
671
- * @param {Boolean} [options.cancel] Set to `true` to cancel replication.
672
- * @param {Boolean} [options.continuous] Set to `true` for continuous
673
- * replication.
674
- * @param {Boolean} [options.create_target] Set to `true` to create the
675
- * target database.
676
- * @param {String} [options.filter] Filter name for filtered replication.
677
- * Example: "mydesign/myfilter".
678
- * @param {Object} [options.query] Query parameters for filter.
679
- * @param {String[]} [options.doc_ids] Document IDs to replicate.
680
- * @param {String} [options.proxy] Proxy through which to replicate.
681
- * @param {Object} [query] HTTP query options.
682
- * @param {Object} [headers] HTTP headers.
683
- * @param {handler} [callback] Callback function.
684
- * @return {Promise} A Promise, if no callback is provided,
685
- * otherwise `null`.
686
- * @see {@link http://wiki.apache.org/couchdb/Replication|CouchDB Wiki}
687
- */
688
-
689
- Client.prototype.replicate = function (options /* [query], [headers], [callback] */) {
690
- return this._(arguments, 1)("POST", "_replicate", { b: options });
691
- };
692
-
693
- /**
694
- * Methods for CouchDB database.
695
- *
696
- * @param {Client} client Clerk client.
697
- * @param {String} name DB name.
698
- * @param {String} [auth] Authentication header value.
699
- * @constructor
700
- * @memberof clerk
701
- * @return This object for chaining.
702
- */
703
-
704
- function DB (client, name, auth) {
705
- this.client = client;
706
- this.name = name;
707
- this.uri = client.uri + "/" + encodeURIComponent(name);
708
- this.auth = auth;
709
- };
710
-
711
- DB.prototype = new Base();
712
-
713
- /**
714
- * Create database.
715
- *
716
- * @param {Object} [query] HTTP query options.
717
- * @param {Object} [headers] HTTP headers.
718
- * @param {handler} [callback] Callback function.
719
- * @return {Promise} A Promise, if no callback is provided,
720
- * otherwise `null`.
721
- */
722
-
723
- DB.prototype.create = function (/* [query], [headers], [callback] */) {
724
- return this._(arguments)("PUT");
725
- };
726
-
727
- /**
728
- * Destroy database.
729
- *
730
- * @param {Object} [query] HTTP query options.
731
- * @param {Object} [headers] HTTP headers.
732
- * @param {handler} [callback] Callback function.
733
- * @return {Promise} A Promise, if no callback is provided,
734
- * otherwise `null`.
735
- */
736
-
737
- DB.prototype.destroy = function (/* [query], [headers], [callback] */) {
738
- return this._(arguments)("DELETE");
739
- };
740
-
741
- /**
742
- * Get database info.
743
- *
744
- * @param {Object} [query] HTTP query options.
745
- * @param {Object} [headers] HTTP headers.
746
- * @param {handler} [callback] Callback function.
747
- * @return {Promise} A Promise, if no callback is provided,
748
- * otherwise `null`.
749
- */
750
-
751
- DB.prototype.info = function (/* [query], [headers], callback */) {
752
- return this._(arguments)("GET");
753
- };
754
-
755
- /**
756
- * Check if database exists.
757
- *
758
- * @param {Object} [query] HTTP query options.
759
- * @param {Object} [headers] HTTP headers.
760
- * @param {handler} [callback] Callback function.
761
- * @return {Promise} A Promise, if no callback is provided,
762
- * otherwise `null`.
763
- */
764
-
765
- DB.prototype.exists = function (/* [query], [headers], callback */) {
766
- var request = this._(arguments);
767
- request._ = function (err, body, status, headers, req) {
768
- if (status === 404) err = null;
769
- return [err, status === 200, status, headers, req];
770
- };
771
- return request("HEAD");
772
- };
773
-
774
- /**
775
- * Fetch document.
776
- *
777
- * Set `rev` in `query`.
778
- *
779
- * @param {String} id Document ID.
780
- * @param {Object} [query] HTTP query options.
781
- * @param {Boolean} [query.revs] Fetch list of revisions.
782
- * @param {Boolean} [query.revs_info] Fetch detailed revision information.
783
- * @param {Object} [headers] HTTP headers.
784
- * @param {handler} [callback] Callback function.
785
- * @return {Promise} A Promise, if no callback is provided,
786
- * otherwise `null`.
787
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#GET|CouchDB Wiki}
788
- */
789
-
790
- DB.prototype.get = function (/* [id], [query], [headers], [callback] */) {
791
- return this._(arguments)("GET");
792
- };
793
-
794
- /**
795
- * Get document metadata.
796
- *
797
- * @param {String} id Document ID.
798
- * @param {Object} [query] HTTP query options.
799
- * @param {Object} [headers] HTTP headers.
800
- * @param {handler} [callback] Callback function.
801
- * @return {Promise} A Promise, if no callback is provided,
802
- * otherwise `null`.
803
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#HEAD|CouchDB Wiki}
804
- */
805
-
806
- DB.prototype.head = function (/* [id], [query], [headers], callback */) {
807
- var self = this;
808
- var request = self._(arguments);
809
- request._ = function (err, body, status, headers, res) {
810
- return [err, err ? null : {
811
- _id: request.p,
812
- _rev: headers.etag && JSON.parse(headers.etag),
813
- contentType: headers["content-type"],
814
- contentLength: headers["content-length"]
815
- }, status, headers, res];
816
- };
817
- return request("HEAD");
818
- };
819
-
820
- /**
821
- * Post document(s) to database.
822
- *
823
- * If documents have no ID, a document ID will be automatically generated
824
- * on the server. Attachments are not currently supported.
825
- *
826
- * @param {Object|Object[]} doc Document or array of documents.
827
- * @param {String} [doc._id] Document ID. If set, uses given document ID.
828
- * @param {String} [doc._rev] Document revision. If set, allows update to
829
- * existing document.
830
- * @param {Object} [doc._attachments] Attachments. If given, must be a
831
- * map of filenames to attachment properties.
832
- * @param {String} [doc._attachments[filename]] Attachment filename, as
833
- * hash key.
834
- * @param {String} [doc._attachments[filename].contentType] Attachment
835
- * MIME content type.
836
- * @param {String|Object} [doc._attachments[filename].data] Attachment
837
- * data. Will be Base64 encoded.
838
- * @param {Object} [query] HTTP query options.
839
- * @param {Boolean} [query.batch] Allow server to write document in
840
- * batch mode. Documents will not be written to disk immediately,
841
- * increasing the chances of write failure.
842
- * @param {Boolean} [query.all_or_nothing] For batch updating of
843
- * documents, use all-or-nothing semantics.
844
- * @param {Object} [headers] HTTP headers.
845
- * @param {handler} [callback] Callback function.
846
- * @return {Promise} A Promise, if no callback is provided,
847
- * otherwise `null`.
848
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#POST|CouchDB Wiki}
849
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API|CouchDB Wiki}
850
- */
851
-
852
- DB.prototype.post = function (docs /* [query], [headers], [callback] */) {
853
- var request = this._(arguments, 1);
854
- if (isArray(docs)) {
855
- request.p = "_bulk_docs";
856
- request.b = extend({ docs: docs }, request.q);
857
- request.q = null
858
- } else {
859
- request.b = docs;
860
- }
861
- return request("POST");
862
- };
863
-
864
- /**
865
- * Put document in database.
866
- *
867
- * @param {Object} doc Document data. Requires `_id` and `_rev`.
868
- * @param {String} [options] Options.
869
- * @param {Object} [query] HTTP query options.
870
- * @param {Object} [headers] HTTP headers.
871
- * @param {handler} [callback] Callback function.
872
- * @return {Promise} A Promise, if no callback is provided,
873
- * otherwise `null`.
874
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#PUT|CouchDB Wiki}
875
- */
876
-
877
- DB.prototype.put = function (/* [id], [doc], [query], [headers], [callback] */) {
878
- var request = this._(arguments, 0, 1);
879
- // prevent acidentally creating database
880
- if (!request.p) request.p = request.b._id || request.b.id;
881
- if (!request.p) throw new Error("missing id");
882
- return request("PUT");
883
- };
884
-
885
- /**
886
- * Delete document(s).
887
- *
888
- * @param {Object|Object[]} docs Document or array of documents.
889
- * @param {Object} [query] HTTP query options.
890
- * @param {Object} [headers] HTTP headers.
891
- * @param {handler} [callback] Callback function.
892
- * @return {Promise} A Promise, if no callback is provided,
893
- * otherwise `null`.
894
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#DELETE|CouchDB Wiki}
895
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API|CouchDB Wiki}
896
- */
897
-
898
- DB.prototype.del = function (docs /* [query], [headers], [callback] */) {
899
- if (isArray(docs)) {
900
- var i = 0, len = docs.length, doc;
901
- for (; i < len; i++) {
902
- doc = docs[i], docs[i] = {
903
- _id: doc._id || doc.id,
904
- _rev: doc._rev || doc.rev,
905
- _deleted: true
906
- };
907
- }
908
- return this.post.apply(this, arguments);
909
- } else {
910
- var request = this._(arguments, 0, 1);
911
- // prevent acidentally deleting database
912
- if (!request.p) throw new Error("missing id");
913
- return request("DELETE");
914
- }
915
- };
916
-
917
- /**
918
- * Copy document.
919
- *
920
- * @param {Object} source Source document.
921
- * @param {String} source.id Source document ID.
922
- * @param {String} [source.rev] Source document revision.
923
- * @param {String} [source._id] Source document ID. Alternate key for
924
- * `source.id`.
925
- * @param {String} [source._rev] Source document revision. Alternate key
926
- * for `source.id`.
927
- * @param {Object} target Target document.
928
- * @param {String} target.id Target document ID.
929
- * @param {String} [target.rev] Target document revision.
930
- * @param {String} [target._id] Target document ID. Alternate key for
931
- * `target.id`.
932
- * @param {String} [target._rev] Target document revision. Alternate key
933
- * for `target.id`.
934
- * @param {Object} [query] HTTP query options.
935
- * @param {Object} [headers] HTTP headers.
936
- * @param {handler} [callback] Callback function.
937
- * @return {Promise} A Promise, if no callback is provided,
938
- * otherwise `null`.
939
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#COPY|CouchDB Wiki}
940
- */
941
-
942
- DB.prototype.copy = function (source, target /* [query], [headers], [callback] */) {
943
- var request = this._(arguments, 2);
944
- var sourcePath = encodeURIComponent(source.id || source._id || source);
945
- var targetPath = encodeURIComponent(target.id || target._id || target);
946
- var sourceRev = source.rev || source._rev;
947
- var targetRev = target.rev || target._rev;
948
-
949
- if (sourceRev) request.q.rev = sourceRev;
950
- if (targetRev) targetPath += "?rev=" + encodeURIComponent(targetRev);
951
-
952
- request.h.Destination = targetPath;
953
-
954
- return request("COPY", sourcePath);
955
- };
956
-
957
- /**
958
- * Query all documents by ID.
959
- *
960
- * @param {Object} [query] HTTP query options.
961
- * @param {JSON} [query.startkey] Start returning results from this
962
- * document ID.
963
- * @param {JSON} [query.endkey] Stop returning results at this document
964
- * ID.
965
- * @param {Integer} [query.limit] Limit number of results returned.
966
- * @param {Boolean} [query.descending=false] Lookup results in reverse
967
- * order by key, returning documents in descending order by key.
968
- * @param {Integer} [query.skip] Skip this many records before
969
- * returning results.
970
- * @param {Boolean} [query.include_docs=false] Include document source for
971
- * each result.
972
- * @param {Boolean} [query.include_end=true] Include `query.endkey`
973
- * in results.
974
- * @param {Boolean} [query.update_seq=false] Include sequence value
975
- * of the database corresponding to the view.
976
- * @param {Object} [headers] HTTP headers.
977
- * @param {handler} [callback] Callback function.
978
- * @return {Promise} A Promise, if no callback is provided,
979
- * otherwise `null`.
980
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API|CouchDB Wiki}
981
- */
982
-
983
- DB.prototype.all = function (/* [query], [headers], [callback] */) {
984
- var request = this._(arguments);
985
- var body = this._viewOptions(request.q);
986
- return request(body ? "POST" : "GET", "_all_docs", { b: body });
987
- };
988
-
989
- /**
990
- * Query a view.
991
- *
992
- * @param {String|Object} view View name (e.g. mydesign/myview) or
993
- * temporary view definition. Using a temporary view is strongly not
994
- * recommended for production use.
995
- * @param {Object} [query] HTTP query options.
996
- * @param {JSON} [query.key] Key to lookup.
997
- * @param {JSON} [query.startkey] Start returning results from this key.
998
- * @param {String} [query.startkey_docid] Start returning results
999
- * from this document ID. Allows pagination with duplicate keys.
1000
- * @param {JSON} [query.endkey] Stop returning results at this key.
1001
- * @param {String} [query.endkey_docid] Stop returning results at
1002
- * this document ID. Allows pagination with duplicate keys.
1003
- * @param {Integer} [query.limit] Limit number of results returned.
1004
- * @param {Boolean|String} [query.stale] Do not refresh view even if
1005
- * stale. For CouchDB versions `1.1.0` and up, set to `update_after` to
1006
- * update view after results are returned.
1007
- * @param {Boolean} [query.descending=false] Lookup results in reverse
1008
- * order by key, returning documents in descending order by key.
1009
- * @param {Integer} [query.skip] Skip this many records before
1010
- * returning results.
1011
- * @param {Boolean|Integer} [query.group=false] Use the reduce function
1012
- * to group results by key. Set to an integer specify `group_level`.
1013
- * @param {Boolean|Integer} [query.reduce=true] Use the reduce function.
1014
- * @param {Boolean} [query.fetch=false] Include document source for
1015
- * each result.
1016
- * @param {Boolean} [query.include_end=true] Include `query.endkey`
1017
- * in results.
1018
- * @param {Boolean} [query.update_seq=false] Include sequence value
1019
- * of the database corresponding to the view.
1020
- * @param {Object} [headers] HTTP headers.
1021
- * @param {handler} [callback] Callback function.
1022
- * @return {Promise} A Promise, if no callback is provided,
1023
- * otherwise `null`.
1024
- * @see {@link http://wiki.apache.org/couchdb/HTTP_view_API|CouchDB Wiki}
1025
- */
1026
-
1027
- DB.prototype.find = function (view /* [query], [headers], [callback] */) {
1028
- var request = this._(arguments, 1), path, body;
1029
-
1030
- if (isString(view)) {
1031
- path = view.split("/", 2);
1032
- path = "_design/" + encodeURIComponent(path[0]) +
1033
- "/_view/" + encodeURIComponent(path[1]);
1034
- } else {
1035
- path = "_temp_view";
1036
- body = view;
1037
- }
1038
-
1039
- body = this._viewOptions(request.q, body);
1040
- return request(body ? "POST" : "GET", path, { b: body });
1041
- };
1042
-
1043
- /**
1044
- * Get database changes.
1045
- *
1046
- * The `feed` option determines how the callback is called:
1047
- *
1048
- * - `normal` calls the callback once.
1049
- * - `longpoll` waits for a response, then calls the callback once.
1050
- * - `continuous` calls the callback each time an update is received.
1051
- * Implemented as the `database#follow()` method.
1052
- *
1053
- * @param {Object} [query] HTTP query options.
1054
- * @param {String} [query.feed="normal"] Type of feed. See comments
1055
- * above.
1056
- * @param {String} [query.filter] Filter updates using this filter.
1057
- * @param {Integer} [query.limit] Maximum number of rows to return.
1058
- * @param {Integer} [query.since=0] Start results from this sequence
1059
- * number.
1060
- * @param {Boolean} [query.include_docs=false] Include documents with
1061
- * results.
1062
- * @param {Integer} [query.timeout=1000] Maximum period in milliseconds
1063
- * to wait for a change before sending a response, even if there are no
1064
- * results.
1065
- * @param {Integer} [query.heartbeat=1000] Period in milliseconds after
1066
- * which an empty line is sent. Applicable only to feed types
1067
- * `longpoll` and `continuous`. Overrides `query.timeout` to keep the
1068
- * feed alive indefinitely.
1069
- * @param {Object} [headers] HTTP headers.
1070
- * @param {handler} [callback] Callback function.
1071
- * @return {Promise} A Promise, if no callback is provided,
1072
- * otherwise `null`.
1073
- * @see {@link http://wiki.apache.org/couchdb/HTTP_database_API#Changes|CouchDB Wiki}
1074
- */
1075
-
1076
- DB.prototype.changes = function (/* [query], [headers], [callback] */) {
1077
- var request = this._(arguments);
1078
- if (request.q.feed != "longpoll") delete request.q.feed;
1079
- return this._changes(request);
1080
- };
1081
-
1082
- /**
1083
- * Follow database changes.
1084
- *
1085
- * @see `#changes()`.
1086
- */
1087
-
1088
- DB.prototype.follow = function (/* [query], [headers], callback */) {
1089
- var self = this;
1090
- var request = this._(arguments);
1091
- var fn = request.f;
1092
-
1093
- if (!fn) return this;
1094
-
1095
- request.q.feed = "longpoll";
1096
- request.f = function (err, body) {
1097
- var args = [].slice.call(arguments);
1098
- var done, i;
1099
- for (i = 0; i < body.length; i++) {
1100
- args[1] = body[i];
1101
- if (done = fn.apply(self, args) === false || err) break;
1102
- }
1103
- if (!done) self._changes(request);
1104
- };
1105
-
1106
- return this._changes(request);
1107
- };
1108
-
1109
- /**
1110
- * Service a changes request.
1111
- *
1112
- * @private
1113
- */
1114
-
1115
- DB.prototype._changes = function (request) {
1116
- return request("GET", "_changes");
1117
- };
1118
-
1119
- /**
1120
- * Update document using server-side handler.
1121
- *
1122
- * @param {String} handler Update handler. Example: mydesign/myhandler
1123
- * @param {String} [id] Document ID.
1124
- * @param {any} data Data.
1125
- * @param {Object} [query] HTTP query options.
1126
- * @param {Object} [headers] Headers.
1127
- * @param {handler} [callback] Callback function.
1128
- * @return {Promise} A Promise, if no callback is provided,
1129
- * otherwise `null`.
1130
- * @see {@link http://wiki.apache.org/couchdb/Document_Update_Handlers|CouchDB Wiki}
1131
- */
1132
-
1133
- DB.prototype.update = function (handler /* [id], [data], [query], [headers], [callback] */) {
1134
- var request = this._(arguments, 1, 1, 1);
1135
- var path = handler.split("/", 2);
1136
-
1137
- path = "_design/" + encodeURIComponent(path[0]) +
1138
- "/_update/" + encodeURIComponent(path[1]);
1139
-
1140
- if (request.p) path += "/" + request.p;
1141
-
1142
- return request("POST", path);
1143
- };
1144
-
1145
- /**
1146
- * Download attachment from document.
1147
- *
1148
- * @param {Object|String} docOrId Document or document ID.
1149
- * @param {String} attachmentName Attachment name.
1150
- * @param {Object} [query] HTTP query options.
1151
- * @param {Object} [headers] HTTP headers.
1152
- * @param {handler} [callback] Callback function.
1153
- * @return {Promise} A Promise, if no callback is provided,
1154
- * otherwise `null`.
1155
- */
1156
-
1157
- DB.prototype.attachment = function (doc, attachmentName /* [query], [headers], [callback] */) {
1158
- var request = this._(arguments, 2);
1159
- var path = encodeURIComponent(doc._id || doc.id || doc) + "/" +
1160
- encodeURIComponent(attachmentName);
1161
- return request("GET", path, options);
1162
- };
1163
-
1164
- /**
1165
- * Upload attachment to document.
1166
- *
1167
- * Set the `Content-Type` header.
1168
- *
1169
- * @param {Object} [doc] Document. Requires `id`. `rev` can be specified
1170
- * here or in `query`.
1171
- * @param {String} attachmentName Attachment name.
1172
- * @param {Object} data Data.
1173
- * @param {Object} [query] HTTP query options.
1174
- * @param {Object} [headers] HTTP headers.
1175
- * @param {handler} [callback] Callback function.
1176
- * @return {Promise} A Promise, if no callback is provided,
1177
- * otherwise `null`.
1178
- */
1179
-
1180
- DB.prototype.attach = function (doc, attachmentName, data /* [query], [headers], [callback] */) {
1181
- var request = this._(arguments, 3);
1182
- request.p = encodeURIComponent(doc._id || doc.id) + "/" +
1183
- encodeURIComponent(attachmentName);
1184
- if (!request.q.rev) request.q.rev = doc._rev || doc.rev;
1185
- request.q.body = data;
1186
- return request("PUT", path);
1187
- };
1188
-
1189
- /**
1190
- * Replicate database.
1191
- *
1192
- * This convenience function sets `options.source` and `options.target` to
1193
- * the selected database name. Either `options.source` or `options.target`
1194
- * must be overridden for a successful replication request.
1195
- *
1196
- * @param {Options} options Options. Accepts all options from
1197
- * `Client.replicate()`.
1198
- * @param {String} [options.source=this.name] Source database URL or
1199
- * local name. Defaults to the selected database name if not given.
1200
- * @param {String} [options.target=this.name] Target database URL or
1201
- * local name. Defaults to the selected database name if not given.
1202
- * @param {Object} [query] HTTP query options.
1203
- * @param {Object} [headers] HTTP headers.
1204
- * @param {handler} [callback] Callback function.
1205
- * @return {Promise} A Promise, if no callback is provided,
1206
- * otherwise `null`.
1207
- */
1208
-
1209
- DB.prototype.replicate = function (options /* [query], [headers], [callback] */) {
1210
- if (!options.source) options.source = this.name;
1211
- if (!options.target) options.target = this.name;
1212
- return this.client.replicate.apply(this.client, arguments);
1213
- };
1214
-
1215
- /**
1216
- * Ensure recent changes are committed to disk.
1217
- *
1218
- * @param {Object} [query] HTTP query options.
1219
- * @param {Object} [headers] HTTP headers.
1220
- * @param {handler} [callback] Callback function.
1221
- * @return {Promise} A Promise, if no callback is provided,
1222
- * otherwise `null`.
1223
- */
1224
-
1225
- DB.prototype.commit = function (/* [query], [headers], [callback] */) {
1226
- return this._(arguments)("POST", "_ensure_full_commit");
1227
- };
1228
-
1229
- /**
1230
- * Purge deleted documents from database.
1231
- *
1232
- * @param {Object} revs Map of document IDs to revisions to be purged.
1233
- * @param {Object} [query] HTTP query options.
1234
- * @param {Object} [headers] HTTP headers.
1235
- * @param {handler} [callback] Callback function.
1236
- * @return {Promise} A Promise, if no callback is provided,
1237
- * otherwise `null`.
1238
- */
1239
-
1240
- DB.prototype.purge = function (revs /* [query], [headers], [callback] */) {
1241
- return this._(arguments, 1)("POST", "_purge", { b: revs });
1242
- };
1243
-
1244
- /**
1245
- * Compact database or design.
1246
- *
1247
- * @param {String} [design] Design name if compacting design indexes.
1248
- * @param {Object} [query] HTTP query options.
1249
- * @param {Object} [headers] HTTP headers.
1250
- * @param {handler} [callback] Callback function.
1251
- * @return {Promise} A Promise, if no callback is provided,
1252
- * otherwise `null`.
1253
- * @see {@link http://wiki.apache.org/couchdb/Compaction|CouchDB Wiki}
1254
- */
1255
-
1256
- DB.prototype.compact = function (/* [design], [query], [headers], [callback] */) {
1257
- var request = this._(arguments);
1258
- return request("POST", "_compact/" + (request.p || ""));
1259
- };
1260
-
1261
- /**
1262
- * Remove unused views.
1263
- *
1264
- * @param {Object} [query] HTTP query options.
1265
- * @param {Object} [headers] HTTP headers.
1266
- * @param {handler} [callback] Callback function.
1267
- * @return {Promise} A Promise, if no callback is provided,
1268
- * otherwise `null`.
1269
- * @see {@link http://wiki.apache.org/couchdb/Compaction|CouchDB Wiki}
1270
- */
1271
-
1272
- DB.prototype.vacuum = function (/* [query], [headers], [callback] */) {
1273
- return this._(arguments)("POST", "_view_cleanup");
1274
- };
1275
-
1276
- /**
1277
- * Parse view options.
1278
- *
1279
- * @param {Object} query The HTTP query options.
1280
- * @param {Object} body The body payload.
1281
- * @param {handler} [callback] Callback function.
1282
- * @return {Object} The body payload.
1283
- * @private
1284
- */
1285
-
1286
- DB.prototype._viewOptions = function (q, body) {
1287
- if (q) {
1288
- if (q.key) q.key = JSON.stringify(q.key);
1289
- if (q.startkey) q.startkey = JSON.stringify(q.startkey);
1290
- if (q.endkey) q.endkey = JSON.stringify(q.endkey);
1291
- if (q.stale && q.stale != "update_after") q.stale = "ok";
1292
- if (q.keys) {
1293
- if (!body) body = {};
1294
- body.keys = q.keys;
1295
- delete q.keys;
1296
- }
1297
- }
1298
- return body;
1299
- };
1300
-
1301
- /**
1302
- * Handle a clerk response.
1303
- *
1304
- * @callback handler
1305
- * @param {Error|null} error Error or `null` on success.
1306
- * @param {Object} data Response data.
1307
- * @param {Integer} status Response status code.
1308
- * @param {Object} headers Response headers.
1309
- * @param {superagent.Response} res Superagent response object.
1310
- */
1311
-
1312
- clerk.Base = Base;
1313
- clerk.Client = Client;
1314
- clerk.DB = DB;
1315
-
1316
- // Export clerk.
1317
- module.exports = clerk;