| 1 |
import triggerFetch from '@wordpress/api-fetch'; |
| 2 |
|
| 3 |
const createRegistryControl = function createRegistryControl( registryControl ) { |
| 4 |
registryControl.isRegistryControl = true; |
| 5 |
|
| 6 |
return registryControl; |
| 7 |
}; |
| 8 |
|
| 9 |
export const apiFetch = ( request ) => { |
| 10 |
return { |
| 11 |
type: 'API_FETCH', |
| 12 |
request, |
| 13 |
}; |
| 14 |
}; |
| 15 |
|
| 16 |
export function select( storeKey, selectorName, ...args ) { |
| 17 |
return { |
| 18 |
type: 'SELECT', |
| 19 |
storeKey, |
| 20 |
selectorName, |
| 21 |
args, |
| 22 |
}; |
| 23 |
} |
| 24 |
|
| 25 |
export function dispatch( storeKey, actionName, ...args ) { |
| 26 |
return { |
| 27 |
type: 'DISPATCH', |
| 28 |
storeKey, |
| 29 |
actionName, |
| 30 |
args, |
| 31 |
}; |
| 32 |
} |
| 33 |
|
| 34 |
const resolveSelect = ( registry, { storeKey, selectorName, args } ) => { |
| 35 |
return new Promise( ( resolve ) => { |
| 36 |
const hasFinished = () => registry.select( '' ) |
| 37 |
.hasFinishedResolution( storeKey, selectorName, args ); |
| 38 |
|
| 39 |
const getResult = () => registry.select( storeKey )[ selectorName ] |
| 40 |
.apply( null, args ); |
| 41 |
|
| 42 |
const result = getResult(); |
| 43 |
|
| 44 |
if ( hasFinished() ) { |
| 45 |
return resolve( result ); |
| 46 |
} |
| 47 |
|
| 48 |
const unsubscribe = registry.subscribe( () => { |
| 49 |
if ( hasFinished() ) { |
| 50 |
unsubscribe(); |
| 51 |
resolve( getResult() ); |
| 52 |
} |
| 53 |
} ); |
| 54 |
} ); |
| 55 |
}; |
| 56 |
|
| 57 |
export const controls = { |
| 58 |
API_FETCH( { request } ) { |
| 59 |
return triggerFetch( request ); |
| 60 |
}, |
| 61 |
SELECT: createRegistryControl( |
| 62 |
( registry ) => ( { storeKey, selectorName, args } ) => { |
| 63 |
return registry.select( storeKey )[ selectorName ].hasResolver |
| 64 |
? resolveSelect( registry, { storeKey, selectorName, args } ) |
| 65 |
: registry.select( storeKey )[ selectorName ]( ...args ); |
| 66 |
} |
| 67 |
), |
| 68 |
DISPATCH: createRegistryControl( |
| 69 |
( registry ) => ( { storeKey, actionName, args } ) => { |
| 70 |
return registry.dispatch( storeKey )[ actionName ]( ...args ); |
| 71 |
} |
| 72 |
), |
| 73 |
}; |
| 74 |
|