From 8bc7adbee4b9333326bb129b32ff1ba18d5fdf81 Mon Sep 17 00:00:00 2001 From: Kelly Dwan Date: Tue, 30 Apr 2019 16:30:43 -0400 Subject: [PATCH] Grid Blocks: Prevent invalid parameter passed to API (https://github.com/woocommerce/woocommerce-blocks/pull/543) * Prevent invalid parameter passed to API per_page cannot be greater than 100, but the frontend does support a larger limit * Add tests --- .../assets/js/utils/get-query.js | 8 +++- .../assets/js/utils/test/get-query.js | 46 +++++++++++++------ 2 files changed, 38 insertions(+), 16 deletions(-) diff --git a/plugins/woocommerce-blocks/assets/js/utils/get-query.js b/plugins/woocommerce-blocks/assets/js/utils/get-query.js index 5ebf3f475ba..794a4a628f0 100644 --- a/plugins/woocommerce-blocks/assets/js/utils/get-query.js +++ b/plugins/woocommerce-blocks/assets/js/utils/get-query.js @@ -1,3 +1,8 @@ +/** + * External dependencies + */ +import { min } from 'lodash'; + export default function getQuery( blockAttributes, name ) { const { attributes, @@ -9,10 +14,11 @@ export default function getQuery( blockAttributes, name ) { } = blockAttributes; const columns = blockAttributes.columns || wc_product_block_data.default_columns; const rows = blockAttributes.rows || wc_product_block_data.default_rows; + const apiMax = Math.floor( 100 / columns ) * columns; // Prevent uneven final row. const query = { status: 'publish', - per_page: rows * columns, + per_page: min( [ rows * columns, apiMax ] ), catalog_visibility: 'visible', }; diff --git a/plugins/woocommerce-blocks/assets/js/utils/test/get-query.js b/plugins/woocommerce-blocks/assets/js/utils/test/get-query.js index f2753e92a8f..cf1c26c577b 100644 --- a/plugins/woocommerce-blocks/assets/js/utils/test/get-query.js +++ b/plugins/woocommerce-blocks/assets/js/utils/test/get-query.js @@ -4,24 +4,40 @@ import getQuery from '../get-query'; describe( 'getQuery', () => { - test( 'should set per_page as a result of row * col', () => { - let query = getQuery( { - columns: 4, - rows: 3, - } ); - expect( query.per_page ).toBe( 12 ); + describe( 'per_page calculations', () => { + test( 'should set per_page as a result of row * col', () => { + let query = getQuery( { + columns: 4, + rows: 3, + } ); + expect( query.per_page ).toBe( 12 ); - query = getQuery( { - columns: 1, - rows: 3, - } ); - expect( query.per_page ).toBe( 3 ); + query = getQuery( { + columns: 1, + rows: 3, + } ); + expect( query.per_page ).toBe( 3 ); - query = getQuery( { - columns: 4, - rows: 1, + query = getQuery( { + columns: 4, + rows: 1, + } ); + expect( query.per_page ).toBe( 4 ); + } ); + + test( 'should restrict per_page to under 100', () => { + let query = getQuery( { + columns: 4, + rows: 30, + } ); + expect( query.per_page ).toBe( 100 ); + + query = getQuery( { + columns: 3, + rows: 87, + } ); + expect( query.per_page ).toBe( 99 ); } ); - expect( query.per_page ).toBe( 4 ); } ); describe( 'for different query orders', () => {