@woocommerce/data
Version:
WooCommerce Admin data store and utilities
71 lines (70 loc) • 2.5 kB
JavaScript
/**
* External dependencies
*/
import { addQueryArgs } from '@wordpress/url';
import { apiFetch } from '@wordpress/data-controls';
import { fetchWithHeaders } from './controls';
function replacer(_, value) {
if (value) {
if (Array.isArray(value)) {
return [...value].sort();
}
if (typeof value === 'object') {
return Object.entries(value)
.sort()
.reduce((current, [propKey, propVal]) => ({
...current,
[propKey]: propVal,
}), {});
}
}
return value;
}
export function getResourceName(prefix, ...identifier) {
const identifierString = JSON.stringify(identifier, replacer).replace(/\\"/g, '"');
return `${prefix}:${identifierString}`;
}
/**
* Generate a resource name for order totals count.
*
* It omits query parameters from the identifier that don't affect
* totals values like pagination and response field filtering.
*
* @param {string} prefix Resource name prefix.
* @param {Object} query Query for order totals count.
* @return {string} Resource name for order totals.
*/
export function getTotalCountResourceName(prefix, query) {
const { _fields, page, per_page, order, orderby, ...totalsQuery } = query;
return getResourceName(prefix, totalsQuery);
}
export function getResourcePrefix(resourceName) {
const hasPrefixIndex = resourceName.indexOf(':');
return hasPrefixIndex < 0
? resourceName
: resourceName.substring(0, hasPrefixIndex);
}
export function isResourcePrefix(resourceName, prefix) {
const resourcePrefix = getResourcePrefix(resourceName);
return resourcePrefix === prefix;
}
export function getResourceIdentifier(resourceName) {
const identifierString = resourceName.substring(resourceName.indexOf(':') + 1);
return JSON.parse(identifierString);
}
export function* request(namespace, query) {
const url = addQueryArgs(namespace, query);
const isUnboundedRequest = query.per_page === -1;
const fetch = isUnboundedRequest ? apiFetch : fetchWithHeaders;
const response = yield fetch({
path: url,
method: 'GET',
});
if (isUnboundedRequest && !('data' in response)) {
return { items: response, totalCount: response.length };
}
if (!isUnboundedRequest && 'data' in response) {
const totalCount = parseInt(response.headers.get('x-wp-total') || '', 10);
return { items: response.data, totalCount };
}
}