From 557e5f879d25cd82e7adc905c804f0841da8a03f Mon Sep 17 00:00:00 2001 From: Sam Beran Date: Thu, 27 Apr 2017 14:26:11 -0500 Subject: [PATCH] Return result accumulator in callback fixes issue: https://github.com/brianc/node-pg-cursor/issues/22 --- README.md | 3 ++- index.js | 3 ++- test/index.js | 11 +++++++++++ 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1cddfbfd..fe79bf74 100644 --- a/README.md +++ b/README.md @@ -59,12 +59,13 @@ pg.connect(function(err, client, done) { Creates an instance of a query cursor. Pass this instance to node-postgres [`client#query`](https://github.com/brianc/node-postgres/wiki/Client#wiki-method-query-parameterized) -#### cursor#read(int rowCount, function callback(Error err, Array rows) +#### cursor#read(int rowCount, function callback(Error err, Array rows, Result result) Read `rowCount` rows from the cursor instance. The `callback` will be called when the rows are available, loaded into memory, parsed, and converted to JavaScript types. If the cursor has read to the end of the result sets all subsequent calls to `cursor#read` will return a 0 length array of rows. I'm open to other ways to signal the end of a cursor, but this has worked out well for me so far. +`result` is a special [https://github.com/brianc/node-postgres/wiki/Query#result-object](Result) object that can be used to accumulate rows. #### cursor#close(function callback(Error err)) diff --git a/index.js b/index.js index 70a90f57..71c12522 100644 --- a/index.js +++ b/index.js @@ -70,7 +70,8 @@ Cursor.prototype._sendRows = function() { //within the call to this callback this._cb = null if(cb) { - cb(null, this._rows) + this._result.rows = this._rows + cb(null, this._rows, this._result) } this._rows = [] }.bind(this)) diff --git a/test/index.js b/test/index.js index 8f04ccc2..af4f041c 100644 --- a/test/index.js +++ b/test/index.js @@ -116,4 +116,15 @@ describe('cursor', function() { }) }) }) + + it('returns result along with rows', function(done) { + var cursor = this.pgCursor(text) + cursor.read(1, function(err, rows, result) { + assert.ifError(err) + assert.equal(rows.length, 1) + assert.strictEqual(rows, result.rows) + assert.deepEqual(result.fields.map(f => f.name), ['num']) + done() + }) + }) })