import { EventSearchRequest , BoosterConfig , Logger , NotAuthorizedError , EventSearchResponse , NotFoundError , EntityMetadata , InvalidParameterError , EventFilter , EventFilterByEntity , EventFilterByType , } from '@boostercloud/framework-types' ; import { BoosterAuth } from './booster-auth' ; import { Booster } from './booster' ; export class BoosterEventsReader { public constructor ( readonly config , readonly logger ) { } public async fetch ( eventRequest ) { this . validateRequest ( eventRequest ) ; return this . processFetch ( eventRequest ) ; } private validateRequest ( eventRequest ) { this . logger . debug ( 'Validating the following event request: ' , eventRequest ) ; const entityMetadata = this . entityMetadataFromRequest ( eventRequest ) ; if ( ! BoosterAuth . isUserAuthorized ( entityMetadata . authorizeReadEvents , eventRequest . currentUser ) ) { throw new NotAuthorizedError ( 'Access denied for reading events' ) ; } } private entityMetadataFromRequest ( eventRequest ) { const { filters } = eventRequest ; if ( ! isByEntitySearch ( filters ) && ! isByEventTypeSearch ( filters ) ) { throw new InvalidParameterError ( 'Invalid event search request. It should contain either "type" or "entity" field, but it included none' ) ; } if ( isByEntitySearch ( filters ) && isByEventTypeSearch ( filters ) ) { throw new InvalidParameterError ( 'Invalid event search request. It should contain either "type" or "entity" field, but it included both' ) ; } if ( isByEntitySearch ( filters ) ) { return this . entityMetadataFromEntityName ( filters . entity ) ; } if ( isByEventTypeSearch ( filters ) ) { return this . entityMetadataFromEventName ( filters . type ) ; } throw new InvalidParameterError ( 'Could not determine event search kind' ) ; } private entityMetadataFromEntityName ( entityName ) { const entityMetadata = this . config . entities [ entityName ] ; if ( ! entityMetadata ) { throw new NotFoundError ( `Could not find entity metadata for "${ entityName }"` ) ; } return entityMetadata ; } private entityMetadataFromEventName ( eventName ) { const reducerMetadata = this . config . reducers [ eventName ] ; if ( ! reducerMetadata ) { throw new NotFoundError ( `Could not find the entity associated to event type "${ eventName }"` ) ; } return this . entityMetadataFromEntityName ( reducerMetadata . class . name ) ; } private async processFetch ( eventRequest ) { return Booster . events ( eventRequest . filters ) ; } } function isByEntitySearch ( filters ) { return 'entity' in filters ; } function isByEventTypeSearch ( filters ) { return 'type' in filters ; }