import { inject , injectable } from 'inversify' ; import * as apid from '../../../api' ; import RecordedHistory from '../../db/entities/RecordedHistory' ; import IPromiseRetry from '../IPromiseRetry' ; import IDBOperator from './IDBOperator' ; import IRecordedHistoryDB from './IRecordedHistoryDB' ; @ injectable ( ) export default class RecordedHistoryDB implements IRecordedHistoryDB { private op : IDBOperator ; private promieRetry : IPromiseRetry ; constructor ( @ inject ( 'IDBOperator' ) op , @ inject ( 'IPromiseRetry' ) promieRetry ) { this . op = op ; this . promieRetry = promieRetry ; } param items return public async restore ( items ) { const connection = await this . op . getConnection ( ) ; const queryRunner = connection . createQueryRunner ( ) ; await queryRunner . startTransaction ( ) ; let hasError = false ; try { await queryRunner . manager . delete ( RecordedHistory , { } ) ; for ( const item of items ) { await queryRunner . manager . insert ( RecordedHistory , item ) ; } await queryRunner . commitTransaction ( ) ; } catch ( err ) { console . error ( err ) ; hasError = err ; await queryRunner . rollbackTransaction ( ) ; } finally { await queryRunner . release ( ) ; } if ( hasError ) { throw new Error ( 'restore error' ) ; } } param program return public async insertOnce ( program ) { const connection = await this . op . getConnection ( ) ; const queryBuilder = connection . createQueryBuilder ( ) . insert ( ) . into ( RecordedHistory ) . values ( program ) ; const insertedResult = await this . promieRetry . run ( ( ) => { return queryBuilder . execute ( ) ; } ) ; return insertedResult . identifiers [ 0 ] . id ; } param time public async delete ( time ) { const connection = await this . op . getConnection ( ) ; const queryBuilder = connection . createQueryBuilder ( ) . delete ( ) . from ( RecordedHistory ) . where ( 'endAt <= :time' , { time : time } ) ; await this . promieRetry . run ( ( ) => { return queryBuilder . execute ( ) ; } ) ; } return public async findAll ( ) { const connection = await this . op . getConnection ( ) ; const queryBuilder = connection . getRepository ( RecordedHistory ) . createQueryBuilder ( ) ; return await this . promieRetry . run ( ( ) => { return queryBuilder . getMany ( ) ; } ) ; } }