From edbeb9e84032eb91fd0488690a5e80028a41f805 Mon Sep 17 00:00:00 2001 From: Kris Zyp Date: Wed, 25 Mar 2015 12:45:29 -0600 Subject: [PATCH] Check parsed results for total property Fixes #113 --- Request.js | 20 +++++++++++++------- tests/Request.js | 9 ++++++++- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/Request.js b/Request.js index bd9516c..c3b7812 100644 --- a/Request.js +++ b/Request.js @@ -135,25 +135,31 @@ define([ headers: headers }); var collection = this; + var parsedResponse = response.then(function (response) { + return collection.parse(response); + }); return { - data: response.then(function (response) { - var results = collection.parse(response); + data: parsedResponse.then(function (data) { // support items in the results - results = results.items || results; + var results = data.items || data; for (var i = 0, l = results.length; i < l; i++) { results[i] = collection._restore(results[i], true); } return results; }), - total: response.response.then(function (response) { - var total = response.data.total; + total: parsedResponse.then(function (data) { + // check for a total property + var total = data.total; if (total > -1) { // if we have a valid positive number from the data, // we can use that return total; } - var range = response.getHeader('Content-Range'); - return range && (range = range.match(/\/(.*)/)) && +range[1]; + // else use headers + return response.response.then(function (response) { + var range = response.getHeader('Content-Range'); + return range && (range = range.match(/\/(.*)/)) && +range[1]; + }); }), response: response.response }; diff --git a/tests/Request.js b/tests/Request.js index e7ea754..5819c22 100644 --- a/tests/Request.js +++ b/tests/Request.js @@ -47,9 +47,16 @@ define([ expected = rangeArgs; results = collection.fetch(); } else { + mockRequest.setResponseHeaders({ + 'Content-Range': rangeArgs.start + '-' + rangeArgs.end + '/' + expectedResults.length + }); results = collection.fetchRange(rangeArgs); + results = results.totalLength.then(function (totalLength) { + assert.strictEqual(totalLength, expectedResults.length); + return results; + }); } - return when(results).then(function (results) { + return results.then(function (results) { expected.headers && mockRequest.assertRequestHeaders(expected.headers); expected.queryParams && mockRequest.assertQueryParams(expected.queryParams);