2019-02-01 09:55:19 +00:00
|
|
|
/** @format */
|
|
|
|
|
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import apiFetch from '@wordpress/api-fetch';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* WooCommerce dependencies
|
|
|
|
*/
|
|
|
|
import { stringifyQuery } from '@woocommerce/navigation';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Internal dependencies
|
|
|
|
*/
|
|
|
|
import { getResourceIdentifier, getResourcePrefix, getResourceName } from '../utils';
|
|
|
|
import { NAMESPACE } from '../constants';
|
|
|
|
|
|
|
|
const typeEndpointMap = {
|
|
|
|
'items-query-categories': 'products/categories',
|
|
|
|
'items-query-customers': 'customers',
|
|
|
|
'items-query-coupons': 'coupons',
|
2019-02-01 10:01:42 +00:00
|
|
|
'items-query-orders': 'orders',
|
2019-02-01 09:55:19 +00:00
|
|
|
'items-query-products': 'products',
|
|
|
|
'items-query-taxes': 'taxes',
|
|
|
|
};
|
|
|
|
|
|
|
|
function read( resourceNames, fetch = apiFetch ) {
|
|
|
|
const filteredNames = resourceNames.filter( name => {
|
|
|
|
const prefix = getResourcePrefix( name );
|
|
|
|
return Boolean( typeEndpointMap[ prefix ] );
|
|
|
|
} );
|
|
|
|
|
|
|
|
return filteredNames.map( async resourceName => {
|
|
|
|
const prefix = getResourcePrefix( resourceName );
|
|
|
|
const endpoint = typeEndpointMap[ prefix ];
|
|
|
|
const query = getResourceIdentifier( resourceName );
|
|
|
|
const url = NAMESPACE + `/${ endpoint }${ stringifyQuery( query ) }`;
|
|
|
|
|
|
|
|
try {
|
2019-03-29 02:45:19 +00:00
|
|
|
const response = await fetch( {
|
|
|
|
parse: false,
|
2019-02-01 09:55:19 +00:00
|
|
|
path: url,
|
|
|
|
} );
|
|
|
|
|
2019-03-29 02:45:19 +00:00
|
|
|
const items = await response.json();
|
2019-02-01 09:55:19 +00:00
|
|
|
const ids = items.map( item => item.id );
|
2019-03-29 02:45:19 +00:00
|
|
|
const totalCount = parseInt( response.headers.get( 'x-wp-total' ) );
|
2019-02-01 09:55:19 +00:00
|
|
|
const itemResources = items.reduce( ( resources, item ) => {
|
|
|
|
resources[ getResourceName( `${ prefix }-item`, item.id ) ] = { data: item };
|
|
|
|
return resources;
|
|
|
|
}, {} );
|
|
|
|
|
|
|
|
return {
|
|
|
|
[ resourceName ]: {
|
|
|
|
data: ids,
|
2019-03-29 02:45:19 +00:00
|
|
|
totalCount,
|
2019-02-01 09:55:19 +00:00
|
|
|
},
|
|
|
|
...itemResources,
|
|
|
|
};
|
|
|
|
} catch ( error ) {
|
|
|
|
return { [ resourceName ]: { error } };
|
|
|
|
}
|
|
|
|
} );
|
|
|
|
}
|
|
|
|
|
|
|
|
export default {
|
|
|
|
read,
|
|
|
|
};
|