From 206e175810aea3eb0d66820eccf2e0e56c232414 Mon Sep 17 00:00:00 2001 From: "K.Adam White" Date: Thu, 11 Sep 2014 22:00:29 -0400 Subject: [PATCH] Fix exception when fetching empty collections This crops up especially easily with search queries: no results, no paging; x-wp-totalpages got set to "0", a string, so the previous null check failed to catch the lack of pagination and an exception occurred when parsing the non-existent link header. --- lib/shared/wp-request.js | 11 +++++++++-- tests/lib/shared/wp-request.js | 30 +++++++++++++++++++++++++++--- 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/lib/shared/wp-request.js b/lib/shared/wp-request.js index a959c07c..2ab239e4 100644 --- a/lib/shared/wp-request.js +++ b/lib/shared/wp-request.js @@ -220,7 +220,14 @@ function mergeUrl( endpoint, linkPath ) { * pagination metadata */ function paginateResponse( result, endpoint ) { - if ( ! result.headers || ! result.headers['x-wp-totalpages'] ) { + if ( ! result.headers || ! result.headers.link ) { + // No headers: return as-is + return result; + } + + var totalPages = result.headers['x-wp-totalpages']; + + if ( ! totalPages || totalPages === '0' || totalPages === '1' ) { // No paging: return as-is return result; } @@ -231,7 +238,7 @@ function paginateResponse( result, endpoint ) { // Store pagination data from response headers on the response collection result.body._paging = { total: result.headers['x-wp-total'], - totalPages: result.headers['x-wp-totalpages'], + totalPages: totalPages, links: links }; diff --git a/tests/lib/shared/wp-request.js b/tests/lib/shared/wp-request.js index 30becc87..494c8a6b 100644 --- a/tests/lib/shared/wp-request.js +++ b/tests/lib/shared/wp-request.js @@ -402,12 +402,36 @@ describe( 'WPRequest', function() { }); }); - it( 'passes data through unchanged if no pagination headers are present', function() { + it( 'passes data through unchanged if no headers are present', function() { mockAgent._response = { - headers: {}, body: 'some object' }; - wpRequest.then(function(parsedResult) { + return wpRequest.then(function(parsedResult) { + expect( parsedResult ).to.equal( 'some object' ); + expect( parsedResult ).not.to.have.property( '_paging' ); + }); + }); + + it( 'passes data through unchanged if header has no link property', function() { + mockAgent._response = { + headers: { + 'x-wp-totalpages': '0', + 'x-wp-total': '0' + }, + body: 'some object' + }; + return wpRequest.then(function(parsedResult) { + expect( parsedResult ).to.equal( 'some object' ); + expect( parsedResult ).not.to.have.property( '_paging' ); + }); + }); + + it( 'passes data through unchanged if pagination header is unset or empty', function() { + mockAgent._response = { + headers: { link: '' }, + body: 'some object' + }; + return wpRequest.then(function(parsedResult) { expect( parsedResult ).to.equal( 'some object' ); expect( parsedResult ).not.to.have.property( '_paging' ); });