import { EventEmitter } from 'events'; import { ApplicationConfiguration } from './configuration'; import { Transaction, TRANSACTION_EVENTS } from './transaction'; import { TransactionTransporter, DefaultTransactionTransporter, TRANSPORTER_EVENTS } from './transporter'; import { DeveloperKeyValidator, DefaultDeveloperKeyValidator, DEVELOPER_KEY_VALIDATOR_EVENTS } from './developer'; export class ProviderApplication extends EventEmitter { private config: ApplicationConfiguration; private transporter: TransactionTransporter; private validator: DeveloperKeyValidator; constructor(config: ApplicationConfiguration) { super(); this.config = config; this.transporter = new DefaultTransactionTransporter(this.config); this.validator = new DefaultDeveloperKeyValidator(this.config); } start(): Promise { return new Promise((resolve, reject) => { if (this.transporter) { // Propagate all transporter events for (const event of Object.values(TRANSPORTER_EVENTS)) { this.transporter.on(event, data => this.emit(event, data)); } this.transporter.start(); } if (this.validator) { // Propagate all developer key validator events for (const event of Object.values(DEVELOPER_KEY_VALIDATOR_EVENTS)) { this.validator.on(event, data => this.emit(event, data)); } this.validator.start(); this.validator.once(DEVELOPER_KEY_VALIDATOR_EVENTS.UPDATE_SUCCESS, () => { resolve(this); }); this.validator.once(DEVELOPER_KEY_VALIDATOR_EVENTS.UPDATE_ERROR, () => { reject(this); }); } else { resolve(this); } }); } async stop(): Promise { if (this.transporter) { this.transporter.stop(); for (const event of Object.values(TRANSPORTER_EVENTS)) { this.transporter.removeAllListeners(event); } } if (this.validator) { this.validator.stop(); for (const event of Object.values(DEVELOPER_KEY_VALIDATOR_EVENTS)) { this.validator.removeAllListeners(event); } } return this; } startTransaction(name: string): Transaction { const transaction = new Transaction(name, this.config); // Propagate all transaction events for (const event of Object.values(TRANSACTION_EVENTS)) { transaction.on(event, () => this.emit(event, transaction)); } this.transporter.push(transaction); return transaction.start(); } setTransactionTransporter(transporter: TransactionTransporter): void { this.transporter = transporter; } setDeveloperKeyValidator(validator: DeveloperKeyValidator): void { this.validator = validator; } isValidDeveloperKey(developerKey: string): boolean { return this.validator.isValidDeveloperKey(developerKey); } validateDeveloperKey(developerKey: string): Error | null { return this.validator.validateDeveloperKey(developerKey); } }