import { v4 as uuidv4 } from 'uuid'; import { ApplicationConfiguration } from './configuration'; import { QueueEntity } from './queue-entity'; import { CreateTransactionPayload } from './protos/types/transaction'; const EVENTS = { STARTED: Symbol(), FINISHED: Symbol(), CANCELLED: Symbol(), }; export const TRANSACTION_EVENTS = EVENTS; export interface TransactionMetadata { [key: string]: any; } export class Transaction extends QueueEntity { public parent: Transaction; public name: string; public trackingKey: string; public developerKey: string; public metadata: TransactionMetadata = {}; public startedAt: Date; public finishedAt: Date; public cancelledAt: Date; private config: ApplicationConfiguration; get isFinished(): boolean { return this.startedAt !== undefined && this.finishedAt !== undefined; } get isCancelled(): boolean { return this.cancelledAt !== undefined; } constructor(name: string, config: ApplicationConfiguration) { super(); this.config = config; this.trackingKey = uuidv4(); this.name = name; } public start(): Transaction { if (this.isCancelled) { throw new Error('Transaction already cancelled at ' + this.cancelledAt); } this.startedAt = new Date(); this.emit(EVENTS.STARTED); return this; } public finish(): Transaction { if (this.isCancelled) { throw new Error('Transaction already cancelled at ' + this.cancelledAt); } if (this.isFinished) { throw new Error('Transaction already finished at ' + this.finishedAt); } if (!this.startedAt) { throw new Error('Transaction was never started'); } this.finishedAt = new Date(); this.emit(EVENTS.FINISHED); this.enqueue(); return this; } public cancel(): this { if (this.isFinished) { throw new Error('Transaction already finished at ' + this.finishedAt); } this.cancelledAt = this.cancelledAt || new Date(); this.emit(EVENTS.CANCELLED); super.cancel(); return this; } public withDeveloperKey(developerKey: string): Transaction { this.developerKey = developerKey; return this; } public withMetadata(metadata: TransactionMetadata): Transaction { this.metadata = { ...this.metadata, ...metadata }; return this; } public fromTransaction(transaction: Transaction): Transaction { this.parent = transaction; return this; } public toMessage(): CreateTransactionPayload { return { applicationKey: this.config.key, developerKey: this.developerKey, name: this.name, trackingKey: this.trackingKey, parentTrackingKey: this.parent ? this.parent.trackingKey : '', startedAt: this.startedAt.getTime(), finishedAt: this.finishedAt.getTime(), metadata: this.metadata }; } }