injectable-job-queue-strategy.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { Injector } from '../common';
  2. import { Job } from './job';
  3. import { JobData } from './types';
  4. type ProcessFunc<Data extends JobData<Data> = {}> = (job: Job<Data>) => Promise<any>;
  5. /**
  6. * @description
  7. * This is a helper class for implementations of {@link JobQueueStrategy} that need to
  8. * have init called before they can start a queue.
  9. * It simply collects calls to {@link JobQueueStrategy} `start()` and calls `start()` again after init.
  10. * When using the class `start()` should start with this snippet
  11. *
  12. * ```
  13. * Typescript
  14. * if (!this.hasInitialized) {
  15. * this.started.set(queueName, process);
  16. * return;
  17. * }
  18. * ```
  19. */
  20. export abstract class InjectableJobQueueStrategy {
  21. protected started = new Map<string, ProcessFunc<any>>();
  22. protected hasInitialized = false;
  23. init(injector: Injector) {
  24. this.hasInitialized = true;
  25. for (const [queueName, process] of this.started) {
  26. this.start(queueName, process);
  27. }
  28. this.started.clear();
  29. }
  30. destroy() {
  31. this.hasInitialized = false;
  32. }
  33. abstract start<Data extends JobData<Data> = {}>(
  34. queueName: string,
  35. process: (job: Job<Data>) => Promise<any>,
  36. ): void;
  37. }