import { BoosterConfig , FilterFor , Logger , OptimisticConcurrencyUnexpectedVersionError , ReadModelEnvelope , ReadModelInterface , ReadOnlyNonEmptyArray , UUID , } from '@boostercloud/framework-types' ; import { ReadModelRegistry } from '../services/read-model-registry' ; import { queryRecordFor } from './searcher-adapter' ; export async function rawReadModelEventsToEnvelopes ( config , logger , rawEvents ) { return rawEvents as Array < ReadModelEnvelope > ; } export async function fetchReadModel ( db , _config , logger , readModelName , readModelID ) { const response = await db . query ( { typeName : readModelName , 'value.id' : readModelID } ) ; const item = response [ 0 ] ; if ( ! item ) { logger . debug ( `[ReadModelAdapter#fetchReadModel] Read model ${ readModelName } with ID ${ readModelID } not found` ) ; } else { logger . debug ( `[ReadModelAdapter#fetchReadModel] Loaded read model ${ readModelName } with ID ${ readModelID } with result:` , item . value ) ; } return [ item ?. value ] ; } export async function storeReadModel ( db , _config , logger , readModelName , readModel , expectedCurrentVersion ) { logger . debug ( '[ReadModelAdapter#storeReadModel] Storing readModel ' + JSON . stringify ( readModel ) ) ; try { await db . store ( { typeName : readModelName , value : readModel } as ReadModelEnvelope ) ; } catch ( e ) { if ( e . name == 'TODO' ) { throw new OptimisticConcurrencyUnexpectedVersionError ( e . message ) ; } throw e ; } logger . debug ( '[ReadModelAdapter#storeReadModel] Read model stored' ) ; } export async function searchReadModel ( db , _config , logger , readModelName , filters ) { logger . debug ( 'Converting filter to query' ) ; const query = queryRecordFor ( readModelName , filters ) ; logger . debug ( 'Got query ' , query ) ; const result = await db . query ( query ) ; logger . debug ( '[ReadModelAdapter#searchReadModel] Search result: ' , result ) ; return result ?. map ( ( envelope ) => envelope . value ) ?? [ ] ; }