Load backend experiments

This commit is contained in:
Moon 2022-02-24 12:21:40 -08:00
parent 35514813c8
commit a7c8e91280
1 changed files with 40 additions and 5 deletions

View File

@ -1,24 +1,59 @@
/**
* External dependencies
*/
import { apiFetch } from '@wordpress/data-controls';
/** /**
* Internal dependencies * Internal dependencies
*/ */
import { setExperiments } from './actions'; import { setExperiments } from './actions';
import { EXPERIMENT_NAME_PREFIX } from './constants'; import {
EXPERIMENT_NAME_PREFIX,
TRANSIENT_NAME_PREFIX,
API_NAMESPACE,
} from './constants';
export function* getExperiments() { function getExperimentsFromFrontend() {
const storageItems = Object.entries( { ...window.localStorage } ).filter( const storageItems = Object.entries( { ...window.localStorage } ).filter(
( item ) => { ( item ) => {
return item[ 0 ].indexOf( EXPERIMENT_NAME_PREFIX ) === 0; return item[ 0 ].indexOf( EXPERIMENT_NAME_PREFIX ) === 0;
} }
); );
const experiments = storageItems.map( ( storageItem ) => { return storageItems.map( ( storageItem ) => {
const [ key, value ] = storageItem; const [ key, value ] = storageItem;
const objectValue = JSON.parse( value ); const objectValue = JSON.parse( value );
return { return {
name: key.replace( EXPERIMENT_NAME_PREFIX, '' ), name: key.replace( EXPERIMENT_NAME_PREFIX, '' ),
variation: objectValue.variationName || 'control', variation: objectValue.variationName || 'control',
source: 'frontend',
}; };
} ); } );
}
yield setExperiments( experiments );
export function* getExperiments() {
try {
const response = yield apiFetch( {
path: `${ API_NAMESPACE }/options?search=_transient_abtest_variation_`,
} );
const experimentsFromBackend = response.map( ( experiment ) => {
return {
name: experiment.option_name.replace(
TRANSIENT_NAME_PREFIX,
''
),
variation:
experiment.option_value === 'control'
? 'control'
: 'treatment',
source: 'backend',
};
} );
yield setExperiments(
getExperimentsFromFrontend().concat( experimentsFromBackend )
);
} catch ( error ) {
throw new Error();
}
} }