2018-12-05 17:10:54 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
2019-07-16 08:56:24 +00:00
|
|
|
import { addQueryArgs } from '@wordpress/url';
|
2018-12-05 17:10:54 +00:00
|
|
|
import apiFetch from '@wordpress/api-fetch';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Internal dependencies
|
|
|
|
*/
|
|
|
|
import { getResourceIdentifier, getResourcePrefix } from '../../utils';
|
|
|
|
import { NAMESPACE } from '../../constants';
|
|
|
|
|
|
|
|
const typeEndpointMap = {
|
|
|
|
'report-items-query-orders': 'orders',
|
|
|
|
'report-items-query-revenue': 'revenue',
|
|
|
|
'report-items-query-products': 'products',
|
|
|
|
'report-items-query-categories': 'categories',
|
|
|
|
'report-items-query-coupons': 'coupons',
|
|
|
|
'report-items-query-taxes': 'taxes',
|
2018-12-05 23:55:13 +00:00
|
|
|
'report-items-query-variations': 'variations',
|
2018-12-19 11:18:43 +00:00
|
|
|
'report-items-query-downloads': 'downloads',
|
2018-12-12 01:52:50 +00:00
|
|
|
'report-items-query-customers': 'customers',
|
2018-12-14 23:58:08 +00:00
|
|
|
'report-items-query-stock': 'stock',
|
2019-01-17 14:08:59 +00:00
|
|
|
'report-items-query-performance-indicators': 'performance-indicators',
|
2018-12-05 17:10:54 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
function read( resourceNames, fetch = apiFetch ) {
|
2020-02-14 02:23:21 +00:00
|
|
|
const filteredNames = resourceNames.filter( ( name ) => {
|
2018-12-05 17:10:54 +00:00
|
|
|
const prefix = getResourcePrefix( name );
|
|
|
|
return Boolean( typeEndpointMap[ prefix ] );
|
|
|
|
} );
|
|
|
|
|
2020-02-14 02:23:21 +00:00
|
|
|
return filteredNames.map( async ( resourceName ) => {
|
2018-12-05 17:10:54 +00:00
|
|
|
const prefix = getResourcePrefix( resourceName );
|
|
|
|
const endpoint = typeEndpointMap[ prefix ];
|
|
|
|
const query = getResourceIdentifier( resourceName );
|
2018-12-05 19:10:43 +00:00
|
|
|
const fetchArgs = {
|
|
|
|
parse: false,
|
2019-07-16 08:56:24 +00:00
|
|
|
path: addQueryArgs( `${ NAMESPACE }/reports/${ endpoint }`, query ),
|
2018-12-05 19:10:43 +00:00
|
|
|
};
|
2018-12-05 17:10:54 +00:00
|
|
|
|
|
|
|
try {
|
2018-12-05 19:10:43 +00:00
|
|
|
const response = await fetch( fetchArgs );
|
2018-12-05 17:10:54 +00:00
|
|
|
const report = await response.json();
|
2020-02-14 02:23:21 +00:00
|
|
|
const totalResults = parseInt(
|
|
|
|
response.headers.get( 'x-wp-total' ), 10
|
|
|
|
);
|
|
|
|
const totalPages = parseInt(
|
|
|
|
response.headers.get( 'x-wp-totalpages' ), 10
|
|
|
|
);
|
2018-12-05 17:10:54 +00:00
|
|
|
|
|
|
|
return {
|
|
|
|
[ resourceName ]: {
|
|
|
|
data: report,
|
|
|
|
totalResults,
|
|
|
|
totalPages,
|
|
|
|
},
|
|
|
|
};
|
|
|
|
} catch ( error ) {
|
|
|
|
return { [ resourceName ]: { error } };
|
|
|
|
}
|
|
|
|
} );
|
|
|
|
}
|
|
|
|
|
|
|
|
export default {
|
|
|
|
read,
|
|
|
|
};
|