From 36e0831ac82f0dce601fab73c6b328dc065c3cef Mon Sep 17 00:00:00 2001 From: Paul Sealock Date: Mon, 1 Apr 2019 13:47:52 +1300 Subject: [PATCH] getItems: modify parse flag by isUnboundedRequest --- .../client/wc-api/items/operations.js | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/plugins/woocommerce-admin/client/wc-api/items/operations.js b/plugins/woocommerce-admin/client/wc-api/items/operations.js index 862c5c73e82..6ab2a9ec406 100644 --- a/plugins/woocommerce-admin/client/wc-api/items/operations.js +++ b/plugins/woocommerce-admin/client/wc-api/items/operations.js @@ -36,16 +36,36 @@ function read( resourceNames, fetch = apiFetch ) { const endpoint = typeEndpointMap[ prefix ]; const query = getResourceIdentifier( resourceName ); const url = NAMESPACE + `/${ endpoint }${ stringifyQuery( query ) }`; + const isUnboundedRequest = -1 === query.per_page; try { const response = await fetch( { - parse: false, + /* eslint-disable max-len */ + /** + * A false parse flag allows a full response including headers which are useful + * to determine totalCount. However, this invalidates an unbounded request, ie + * `per_page: -1` by skipping middleware in apiFetch. + * + * See the Gutenberg code for more: + * https://github.com/WordPress/gutenberg/blob/dee3dcf49028717b4af3164e3096bfe747c41ed2/packages/api-fetch/src/middlewares/fetch-all-middleware.js#L39-L45 + */ + /* eslint-enable max-len */ + parse: isUnboundedRequest, path: url, } ); - const items = await response.json(); + let items; + let totalCount; + + if ( isUnboundedRequest ) { + items = response; + totalCount = items.length; + } else { + items = await response.json(); + totalCount = parseInt( response.headers.get( 'x-wp-total' ) ); + } + const ids = items.map( item => item.id ); - const totalCount = parseInt( response.headers.get( 'x-wp-total' ) ); const itemResources = items.reduce( ( resources, item ) => { resources[ getResourceName( `${ prefix }-item`, item.id ) ] = { data: item }; return resources;