2018-12-13 19:24:54 +00:00
|
|
|
/** @format */
|
|
|
|
|
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import apiFetch from '@wordpress/api-fetch';
|
|
|
|
import { mapValues, pick } from 'lodash';
|
|
|
|
|
|
|
|
function read( resourceNames, fetch = apiFetch ) {
|
|
|
|
return [ ...readCurrentUserData( resourceNames, fetch ) ];
|
|
|
|
}
|
|
|
|
|
|
|
|
function update( resourceNames, data, fetch = apiFetch ) {
|
|
|
|
return [ ...updateCurrentUserData( resourceNames, data, fetch ) ];
|
|
|
|
}
|
|
|
|
|
|
|
|
function readCurrentUserData( resourceNames, fetch ) {
|
|
|
|
if ( resourceNames.includes( 'current-user-data' ) ) {
|
|
|
|
const url = '/wp/v2/users/me?context=edit';
|
|
|
|
|
|
|
|
return [
|
|
|
|
fetch( { path: url } )
|
2018-12-13 20:34:23 +00:00
|
|
|
.then( userToUserDataResource )
|
2018-12-13 19:24:54 +00:00
|
|
|
.catch( error => {
|
2018-12-13 20:34:23 +00:00
|
|
|
return { [ 'current-user-data' ]: { error: String( error.message ) } };
|
2018-12-13 19:24:54 +00:00
|
|
|
} ),
|
|
|
|
];
|
|
|
|
}
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
|
|
|
|
function updateCurrentUserData( resourceNames, data, fetch ) {
|
|
|
|
const resourceName = 'current-user-data';
|
2018-12-13 20:34:23 +00:00
|
|
|
const userDataFields = [
|
|
|
|
'categories_report_columns',
|
|
|
|
'coupons_report_columns',
|
|
|
|
'customers_report_columns',
|
|
|
|
'orders_report_columns',
|
|
|
|
'products_report_columns',
|
|
|
|
'revenue_report_columns',
|
|
|
|
'taxes_report_columns',
|
|
|
|
'variations_report_columns',
|
|
|
|
];
|
2018-12-13 19:24:54 +00:00
|
|
|
|
|
|
|
if ( resourceNames.includes( resourceName ) ) {
|
|
|
|
const url = '/wp/v2/users/me';
|
|
|
|
const userData = pick( data[ resourceName ], userDataFields );
|
|
|
|
const meta = mapValues( userData, JSON.stringify );
|
|
|
|
const user = { woocommerce_meta: meta };
|
|
|
|
|
|
|
|
return [
|
|
|
|
fetch( { path: url, method: 'POST', data: user } )
|
2018-12-13 20:34:23 +00:00
|
|
|
.then( userToUserDataResource )
|
2018-12-13 19:24:54 +00:00
|
|
|
.catch( error => {
|
|
|
|
return { [ resourceName ]: { error } };
|
|
|
|
} ),
|
|
|
|
];
|
|
|
|
}
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
|
2018-12-13 20:34:23 +00:00
|
|
|
function userToUserDataResource( user ) {
|
|
|
|
const userData = mapValues( user.woocommerce_meta, data => {
|
|
|
|
if ( ! data || 0 === data.length ) {
|
|
|
|
return '';
|
|
|
|
}
|
|
|
|
return JSON.parse( data );
|
|
|
|
} );
|
|
|
|
return { [ 'current-user-data' ]: { data: userData } };
|
|
|
|
}
|
|
|
|
|
2018-12-13 19:24:54 +00:00
|
|
|
export default {
|
|
|
|
read,
|
|
|
|
update,
|
|
|
|
};
|