All files queue-entity.ts

60.61% Statements 20/33
60% Branches 3/5
57.14% Functions 4/7
60.61% Lines 20/33

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 681x   1x 1x 1x 1x 1x 1x     1x                 1x   1x 4x   4x       4x 4x       3x 3x 3x       1x 1x 1x                                                    
import { EventEmitter } from 'events';
 
export enum QueueEntityState {
  PENDING = 0,
  QUEUED = 1,
  RUNNING = 2,
  FINISHED = 3,
  CANCELLED = 4,
}
 
const EVENTS = {
  ENQUEUE: Symbol(),
  CANCEL: Symbol(),
  PROCESS: Symbol(),
  RETRY: Symbol(),
  FINISHED: Symbol(),
  FAILED: Symbol(),
}
 
export const QUEUE_ENTITY_EVENTS = EVENTS;
 
export class QueueEntity extends EventEmitter {
  public state: QueueEntityState = QueueEntityState.PENDING;
 
  private retries = 0;
  private limit: number;
 
  constructor(limit = 5) {
    super();
    this.limit = limit;
  }
 
  public enqueue(): this {
    this.state = QueueEntityState.QUEUED;
    this.emit(EVENTS.ENQUEUE);
    return this;
  }
 
  public cancel(): this {
    this.state = QueueEntityState.CANCELLED;
    this.emit(EVENTS.CANCEL);
    return this;
  }
 
  public process(): this {
    this.state = QueueEntityState.RUNNING;
    this.emit(EVENTS.PROCESS);
    return this;
  }
 
  public published(metadata: Record<string, any>): this {
    this.state = QueueEntityState.FINISHED;
    this.emit(EVENTS.FINISHED, metadata);
    return this;
  }
 
  public retry(metadata: Record<string, any>): boolean {
    ++this.retries;
    if (this.retries <= this.limit) {
      this.state = QueueEntityState.QUEUED;
      this.emit(EVENTS.RETRY);
      return true;
    }
    this.emit(EVENTS.FAILED, metadata);
    return false;
  }
}