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
This commit is contained in:
Kelly Dwan 2019-04-30 16:30:43 -04:00 committed by GitHub
parent ef50db86f5
commit 8bc7adbee4
2 changed files with 38 additions and 16 deletions

View File

@ -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',
};

View File

@ -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', () => {