import { UUID , UserApp , Logger , BoosterConfig , EventEnvelope , OptimisticConcurrencyUnexpectedVersionError , } from '@boostercloud/framework-types' ; import { retryIfError } from '@boostercloud/framework-common-helpers' ; import { EventRegistry } from '..' ; const originOfTime = new Date ( 0 ) . toISOString ( ) ; export function rawEventsToEnvelopes ( rawEvents ) { return rawEvents . map ( ( event ) => event as EventEnvelope ) ; } export async function readEntityEventsSince ( eventRegistry , config , logger , entityTypeName , entityID , since ? ) { const fromTime = since ? since : originOfTime ; const query = { entityID : entityID , entityTypeName : entityTypeName , kind : 'event' , createdAt : { $gt : fromTime , } , } ; const result = await eventRegistry . query ( query ) ; logger . debug ( `[EventsAdapter#readEntityEventsSince] Loaded events for entity ${ entityTypeName } with ID ${ entityID } with result:` , result ) ; return result ; } export async function readEntityLatestSnapshot ( eventRegistry , config , logger , entityTypeName , entityID ) { const query = { entityID : entityID , entityTypeName : entityTypeName , kind : 'snapshot' , } ; const snapshot = ( await eventRegistry . queryLatest ( query ) ) as EventEnvelope ; if ( snapshot ) { logger . debug ( `[EventsAdapter#readEntityLatestSnapshot] Snapshot found for entity ${ entityTypeName } with ID ${ entityID }:` , snapshot ) ; return snapshot as EventEnvelope ; } else { logger . debug ( `[EventsAdapter#readEntityLatestSnapshot] No snapshot found for entity ${ entityTypeName } with ID ${ entityID }.` ) ; return null ; } } export async function storeEvents ( userApp , eventRegistry , eventEnvelopes , _config , logger ) { logger . debug ( '[EventsAdapter#storeEvents] Storing the following event envelopes:' , eventEnvelopes ) ; for ( const eventEnvelope of eventEnvelopes ) { await retryIfError ( logger , ( ) => persistEvent ( eventRegistry , eventEnvelope ) , OptimisticConcurrencyUnexpectedVersionError ) ; } logger . debug ( '[EventsAdapter#storeEvents] EventEnvelopes stored' ) ; await userApp . boosterEventDispatcher ( eventEnvelopes ) ; } async function persistEvent ( eventRegistry , eventEnvelope ) { try { await eventRegistry . store ( eventEnvelope ) ; } catch ( e ) { throw e ; } }