2018-11-29 15:57:49 +00:00
|
|
|
/** @format */
|
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import { ApiClient } from '@fresh-data/framework';
|
|
|
|
import { createStore as createReduxStore } from 'redux';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Internal dependencies
|
|
|
|
*/
|
|
|
|
import reducer from './reducer';
|
|
|
|
|
|
|
|
function createStore( name ) {
|
|
|
|
const devTools = window.__REDUX_DEVTOOLS_EXTENSION__;
|
|
|
|
|
|
|
|
return createReduxStore( reducer, devTools && devTools( { name: name, instanceId: name } ) );
|
|
|
|
}
|
|
|
|
|
|
|
|
function createDataHandlers( store ) {
|
|
|
|
return {
|
|
|
|
dataRequested: resourceNames => {
|
2019-03-20 02:55:26 +00:00
|
|
|
const { resources } = store.getState();
|
|
|
|
const newResources = resourceNames.some( resourceName => ! resources[ resourceName ] );
|
|
|
|
if ( ! newResources && document.hidden ) {
|
2019-03-04 19:47:48 +00:00
|
|
|
return;
|
|
|
|
}
|
2018-11-29 15:57:49 +00:00
|
|
|
store.dispatch( {
|
|
|
|
type: 'FRESH_DATA_REQUESTED',
|
|
|
|
resourceNames,
|
|
|
|
time: new Date(),
|
|
|
|
} );
|
|
|
|
},
|
|
|
|
dataReceived: resources => {
|
|
|
|
store.dispatch( {
|
|
|
|
type: 'FRESH_DATA_RECEIVED',
|
|
|
|
resources,
|
|
|
|
time: new Date(),
|
|
|
|
} );
|
|
|
|
},
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
function createApiClient( name, apiSpec ) {
|
|
|
|
const store = createStore( name );
|
|
|
|
const dataHandlers = createDataHandlers( store );
|
|
|
|
const apiClient = new ApiClient( apiSpec );
|
|
|
|
apiClient.setDataHandlers( dataHandlers );
|
|
|
|
|
|
|
|
const storeChanged = () => {
|
|
|
|
apiClient.setState( store.getState() );
|
|
|
|
};
|
|
|
|
store.subscribe( storeChanged );
|
|
|
|
|
|
|
|
return apiClient;
|
|
|
|
}
|
|
|
|
|
|
|
|
export default createApiClient;
|