woocommerce/plugins/woocommerce-admin/client/wc-api/reports/items/operations.js

68 lines
1.8 KiB
JavaScript
Raw Normal View History

2018-12-05 17:10:54 +00:00
/**
* External dependencies
*/
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',
'report-items-query-variations': 'variations',
'report-items-query-downloads': 'downloads',
'report-items-query-customers': 'customers',
'report-items-query-stock': 'stock',
'report-items-query-performance-indicators': 'performance-indicators',
2018-12-05 17:10:54 +00:00
};
function read( resourceNames, fetch = apiFetch ) {
const filteredNames = resourceNames.filter( ( name ) => {
2018-12-05 17:10:54 +00:00
const prefix = getResourcePrefix( name );
return Boolean( typeEndpointMap[ prefix ] );
} );
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 );
const fetchArgs = {
parse: false,
path: addQueryArgs( `${ NAMESPACE }/reports/${ endpoint }`, query ),
};
2018-12-05 17:10:54 +00:00
try {
const response = await fetch( fetchArgs );
2018-12-05 17:10:54 +00:00
const report = await response.json();
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,
};