import { PagingParams , parseCursorPagination , properlyOrdered } from "../util/paging" ; import { connection } from "./connection" ; export abstract class BaseStorage { protected searchParams : any ; constructor ( ) { this . searchParams = { query : { bool : { must : [ ] } } } ; } public async all ( pagingParams ? ) { if ( pagingParams ) { this . paginate ( pagingParams ) ; } const docs = await this . search ( this . searchParams ) ; if ( ! docs ) { return [ ] ; } this . searchParams = { query : { bool : { must : [ ] } } } ; return pagingParams ? properlyOrdered ( docs , pagingParams ) : docs ; } public async findById ( id ) { const { body : response } = await connection . get ( { index : this . elasticIndexName , id } ) ; return this . convertRawDoc ( response . _source ) ; } public async one ( ) { this . searchParams . size = 1 ; const docs = await this . search ( this . searchParams ) ; if ( docs . length === 0 ) { return null ; } return this . convertRawDoc ( docs [ 0 ] ) ; } protected abstract get elasticIndexName ( ) : string ; protected abstract convertRawDoc < T > ( doc ) ; protected async search ( requestBody ) { const { body : response } = await connection . search ( { index : this . elasticIndexName , body : requestBody } ) ; return response . hits . hits . map ( ( h ) => { return { ... h . _source , id : this . hitID ( h ) } ; } ) ; } protected hitID ( hit ) { return hit . _id ; } protected async aggregation ( queries ) { const { body : response } = await connection . search ( { index : this . elasticIndexName , body : { aggs : queries } } , { querystring : { size : 0 } } ) ; return response . aggregations ; } protected addTerm ( term ) { this . searchParams . query . bool . must . push ( { term } ) ; return this ; } protected addTerms ( terms ) { this . searchParams . query . bool . must . push ( { terms } ) ; return this ; } protected paginate ( pagingParams ) { const { limit , order , cursor } = parseCursorPagination ( pagingParams ) ; this . searchParams . sort = [ { paging_token : order } ] ; this . searchParams . size = limit ; if ( cursor ) { this . searchParams . query . bool . must . push ( { range : { paging_token : pagingParams . after ? { gt : cursor } : { lt : cursor } } } ) ; } } }