import { Round } from 'shared/model/round' ; import db , { pgpE } from 'shared/driver/db/index' ; import { IRoundPGRepository as IRoundPGRepositoryShared , RawRound } from 'shared/repository/round' ; import queries from 'core/repository/queries/round' ; export interface IRoundPGRepository extends IRoundPGRepositoryShared { } class RoundPGRepository implements IRoundPGRepository { private readonly tableName : string = 'round' ; private readonly tableFields : Array < string > = [ 'height_start' , 'slots' ] ; private readonly columnSet = new pgpE . helpers . ColumnSet ( this . tableFields , { table : this . tableName } ) ; serialize ( round ) { return { height_start : round . startHeight , slots : round . slots } ; } deserialize ( rawRound , radix = 10 ) { return new Round ( { startHeight : parseInt ( rawRound . height_start , radix ) , slots : rawRound . slots } ) ; } async getByHeight ( height ) { const rawRound = await db . oneOrNone ( queries . getByHeight , { height } ) ; if ( ! rawRound ) { return ; } return this . deserialize ( rawRound ) ; } async getLast ( height ) { const rawRound = await db . oneOrNone ( queries . getLast , { height } ) ; if ( ! rawRound ) { return ; } return this . deserialize ( rawRound ) ; } async getMany ( limit , offset ) { const rawRounds = await db . manyOrNone ( queries . getMany , { offset , limit } ) ; if ( ! rawRounds ) { return ; } return rawRounds . map ( rawRound => this . deserialize ( rawRound ) ) ; } async getCount ( ) { const result = await db . one ( queries . getCount ) ; if ( ! result ) { return 0 ; } return result . count ; } async saveOrUpdate ( round ) { const rounds = [ ] . concat ( round ) ; const values = [ ] ; rounds . forEach ( ( roundEntity ) => { values . push ( this . serialize ( roundEntity ) ) ; } ) ; const query = pgpE . helpers . insert ( values , this . columnSet ) + ' ON CONFLICT(height_start) DO UPDATE SET ' + this . columnSet . assignColumns ( { from : 'EXCLUDED' , skip : [ 'height_start' ] } ) ; await db . none ( query ) ; return null ; } async delete ( round ) { await db . none ( queries . deleteByStartHeight , { height : round . startHeight } ) ; } } export default new RoundPGRepository ( ) ;