import * as async from "async" ; import { Table } from "./core/table" ; import { Callback } from "./core/callback" ; import { Command } from "./core/command" ; import { PersistenceError } from "./persistenceError" ; import { FlushPriority } from "./mapping/mappingModel" ; hidden export class Batch implements Command { /**
     * Error that occurred while with building the batch.
     */ error : Error ; private _commandTable : Table < Command > = [ ] ; private _commands : Command [ ] = [ ] ; private _executed = false ; param id returns getCommand ( id ) { return this . _commandTable [ id ] ; } param id param command addCommand ( id , command ) { if ( this . _commandTable [ id ] ) { throw new PersistenceError ( "Batch already contains a command with id '" + id + "'." ) ; } if ( command . priority == null ) { command . priority = FlushPriority . Medium ; } this . _commandTable [ id ] = command ; this . _commands . push ( command ) ; } param callback execute ( callback ) { if ( this . _executed ) { throw new PersistenceError ( "Batch had already been executed." ) ; } this . _executed = true ; if ( this . _commands . length == 0 ) { process . nextTick ( callback ) ; return ; } var self = this ; this . _commands . sort ( commandSorter ) ; executeCommands ( ) ; function executeCommands ( err ? ) { if ( err || self . _commands . length == 0 ) { callback ( err ) ; return ; } var priority = self . _commands [ 0 ] . priority , count = 0 ; while ( count < self . _commands . length && self . _commands [ count ] . priority == priority ) { count ++ ; } async . each ( self . _commands . splice ( 0 , count ) , ( command , done ) => command . execute ( done ) , executeCommands ) ; } } } function commandSorter ( a , b ) { return b . priority - a . priority ; }