From 9ef720c9684949655ba11305f91a7b3806680e63 Mon Sep 17 00:00:00 2001 From: Daniel Burian Date: Wed, 12 Sep 2012 18:05:04 +0200 Subject: [PATCH] Added getDocs. --- README.md | 16 ++++++++++++++++ lib/couchdb.js | 24 ++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/README.md b/README.md index 3b012ab..7bbaab4 100644 --- a/README.md +++ b/README.md @@ -207,6 +207,22 @@ Wrapper for [DELETE /db-name](http://wiki.apache.org/couchdb/HTTP_database_API#D Wrapper for [GET /db-name/doc-id\[?rev=\]\[&attachments=\]](http://wiki.apache.org/couchdb/HTTP_Document_API#GET). Fetches a document with a given `id` and optional `rev` and/or `attachments` from the database. +### db.getDocs(keys/startkey, [endkey]) + +Fetches multiple documents using [/\_all\_docs](http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API#Fetch_Multiple_Documents_With_a_Single_Request). + +Example: + + db.getDocs(['aa', 'bb', 'cc'], function (er, r) { + if (er) throw new Error(JSON.stringify(er)); + // r => {"total_rows":10,"offset":2,"rows":[{...}]} + }); + + db.getDocs('aa', 'cc', function (er, r) { + if (er) throw new Error(JSON.stringify(er)); + // r => {"total_rows":10,"offset":2,"rows":[{...}]} + }); + ### db.saveDoc(id, doc) Wrapper for [PUT /db-name/doc-id](http://wiki.apache.org/couchdb/HTTP_Document_API#PUT). Saves a json `doc` with a given `id`. diff --git a/lib/couchdb.js b/lib/couchdb.js index 7d334f6..42f0b25 100644 --- a/lib/couchdb.js +++ b/lib/couchdb.js @@ -470,6 +470,30 @@ Db.prototype.getDoc = function(id, rev, attachments, cb) { return this.request(request, cb); }; +Db.prototype.getDocs = function (startkey, endkey, cb) { + // if startkey is an array of keys use POST to get docs + if (Array.isArray(startkey) && typeof(endkey) === 'function') { + cb = endkey; + return this.request({ + path: '/_all_docs', + query: {include_docs: true}, + data: {keys:startkey}, + method: 'POST' + }, cb); + } else { + // if startkey and endkey are provided use default GET + var query = { + include_docs: true, + startkey: startkey, + endkey: endkey + } + return this.request({ + path: '/_all_docs', + query: query + }, cb); + } +}; + Db.prototype.saveDoc = function(id, doc, cb) { if (typeof id == 'object') { cb = doc;