cluedin-widget
Version:
This is the project for creating and managing widgets in CluedIn.
145 lines (112 loc) • 3.49 kB
JavaScript
import constants from '../constants';
import { unauthorized } from './generic';
import { getEntity, getLatest, getSuggestedSearch } from '../data/entity';
var entities = {};
var requestEntity = () => {
return {
type: constants.entity.REQUEST_ENTITY
};
};
var receiveEntity = ( entity, addToEntities ) => {
return {
type: constants.entity.RECEIVE_ENTITY,
data: { entity, addToEntities }
};
};
var invalidEntity = () => {
return {
type: constants.entity.INVALID_ENTITY
};
};
var shouldFetchEntity = ( state, id ) => {
return ( !state.entity.selectedEntity || state.entity.selectedEntity.id !== id );
};
var fetchEntity = ( state, id ) => {
return function( dispatch ) {
var entityAlreadyFetch = state.entity.entities[ id ];
if ( entityAlreadyFetch ) {
return dispatch( receiveEntity( entityAlreadyFetch ) );
}
dispatch( requestEntity( id ) );
return getEntity( id ).then( function( resp ) {
if ( !resp ) {
return dispatch( invalidEntity() );
}
dispatch( receiveEntity( resp, true ) );
} ).catch( unauthorized( dispatch, invalidEntity ) );
};
};
var requestGenericLatest = ( type ) => {
return {
type: constants.entity.REQUEST_GENERIC_LATEST,
data: { type }
};
};
var invalidGenericLatest = () => {
return {
type: constants.entity.INVALID_GENERIC_LATEST
};
};
var receiveGenericLatest = ( entities, type ) => {
return {
type: constants.entity.RECEIVE_GENERIC_LATEST,
data: { entities, type }
};
};
export function shouldFetchGenericLatest( type, id ) {
return function( dispatch ) {
dispatch( requestGenericLatest( type ) );
return getLatest( type, id ).then( function( resp ) {
if ( !resp ) {
return dispatch( invalidGenericLatest() );
}
dispatch( receiveGenericLatest( resp, type ) );
} ).catch( unauthorized( dispatch, invalidEntity ) );
};
}
var requestSuggestedSearch = ( search, index ) => {
return {
type: constants.entity.REQUEST_SUGGESTED_SEARCH,
data: {
searchQuery: search,
index: index
}
};
};
var invalidSuggestedSearch = ( search, index ) => {
return {
type: constants.entity.INVALID_SUGGESTED_SEARCH,
data: {
searchQuery: search,
index: index
}
};
};
var receiveSuggestedSearch = ( entities, search, index ) => {
return {
type: constants.entity.RECEIVE_SUGGESTED_SEARCH,
data: {
searchQuery: search,
entities: entities,
index: index
}
}
};
export function shouldFetchSuggestedSearch( search, index ) {
return function( dispatch ) {
dispatch( requestSuggestedSearch( search, index ) );
return getSuggestedSearch( search ).then( function( resp ) {
if ( !resp ) {
return dispatch( invalidSuggestedSearch() );
}
dispatch( receiveSuggestedSearch( resp, search, index ) );
} ).catch( unauthorized( dispatch, invalidSuggestedSearch ) );
};
}
export function shouldFetchEntityIfNeeded( id ) {
return ( dispatch, getState ) => {
if ( shouldFetchEntity( getState(), id ) ) {
return dispatch( fetchEntity( getState(), id ) );
}
};
}