2019-01-31 01:04:11 +00:00
|
|
|
/** @format */
|
|
|
|
|
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import apiFetch from '@wordpress/api-fetch';
|
|
|
|
import { pick } from 'lodash';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Internal dependencies
|
|
|
|
*/
|
|
|
|
import { NAMESPACE } from '../constants';
|
|
|
|
|
|
|
|
function read( resourceNames, fetch = apiFetch ) {
|
|
|
|
return [ ...readSettings( resourceNames, fetch ) ];
|
|
|
|
}
|
|
|
|
|
|
|
|
function update( resourceNames, data, fetch = apiFetch ) {
|
|
|
|
return [ ...updateSettings( resourceNames, data, fetch ) ];
|
|
|
|
}
|
|
|
|
|
|
|
|
function readSettings( resourceNames, fetch ) {
|
|
|
|
if ( resourceNames.includes( 'settings' ) ) {
|
|
|
|
const url = NAMESPACE + '/settings/wc_admin';
|
|
|
|
|
|
|
|
return [
|
|
|
|
fetch( { path: url } )
|
|
|
|
.then( settingsToSettingsResource )
|
|
|
|
.catch( error => {
|
|
|
|
return { [ 'settings' ]: { error: String( error.message ) } };
|
|
|
|
} ),
|
|
|
|
];
|
|
|
|
}
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
|
|
|
|
function updateSettings( resourceNames, data, fetch ) {
|
|
|
|
const resourceName = 'settings';
|
|
|
|
const settingsFields = [ 'woocommerce_excluded_report_order_statuses' ];
|
|
|
|
|
|
|
|
if ( resourceNames.includes( resourceName ) ) {
|
|
|
|
const url = NAMESPACE + '/settings/wc_admin/';
|
|
|
|
const settingsData = pick( data[ resourceName ], settingsFields );
|
|
|
|
|
|
|
|
const promises = Object.keys( settingsData ).map( setting => {
|
|
|
|
return fetch( {
|
|
|
|
path: url + setting,
|
|
|
|
method: 'POST',
|
|
|
|
data: { value: settingsData[ setting ] },
|
|
|
|
} )
|
2019-02-13 11:44:58 +00:00
|
|
|
.then( settingToSettingsResource.bind( null, data.settings ) )
|
2019-01-31 01:04:11 +00:00
|
|
|
.catch( error => {
|
|
|
|
return { [ resourceName ]: { error } };
|
|
|
|
} );
|
|
|
|
} );
|
|
|
|
|
2019-02-13 11:44:58 +00:00
|
|
|
return promises;
|
2019-01-31 01:04:11 +00:00
|
|
|
}
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
|
|
|
|
function settingsToSettingsResource( settings ) {
|
|
|
|
const settingsData = {};
|
|
|
|
settings.forEach( setting => ( settingsData[ setting.id ] = setting.value ) );
|
|
|
|
return { [ 'settings' ]: { data: settingsData } };
|
|
|
|
}
|
|
|
|
|
2019-02-13 11:44:58 +00:00
|
|
|
function settingToSettingsResource( settings, setting ) {
|
|
|
|
settings[ setting.id ] = setting.value;
|
|
|
|
return { [ 'settings' ]: { data: settings } };
|
|
|
|
}
|
|
|
|
|
2019-01-31 01:04:11 +00:00
|
|
|
export default {
|
|
|
|
read,
|
|
|
|
update,
|
|
|
|
};
|