process-context.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { Injectable } from '@nestjs/common';
  2. type ProcessContextType = 'server' | 'worker';
  3. let currentContext: ProcessContextType = 'server';
  4. /**
  5. * @description
  6. * The ProcessContext can be injected into your providers & modules in order to know whether it
  7. * is being executed in the context of the main Vendure server or the worker.
  8. *
  9. * @example
  10. * ```TypeScript
  11. * import { Injectable, OnApplicationBootstrap } from '\@nestjs/common';
  12. * import { ProcessContext } from '\@vendure/core';
  13. *
  14. * \@Injectable()
  15. * export class MyService implements OnApplicationBootstrap {
  16. * constructor(private processContext: ProcessContext) {}
  17. *
  18. * onApplicationBootstrap() {
  19. * if (this.processContext.isServer) {
  20. * // code which will only execute when running in
  21. * // the server process
  22. * }
  23. * }
  24. * }
  25. * ```
  26. *
  27. * @docsCategory common
  28. */
  29. export class ProcessContext {
  30. get isServer(): boolean {
  31. return currentContext === 'server';
  32. }
  33. get isWorker(): boolean {
  34. return currentContext === 'worker';
  35. }
  36. }
  37. /**
  38. * @description
  39. * Should only be called in the core bootstrap functions in order to establish
  40. * the current process context.
  41. *
  42. * @internal
  43. */
  44. export function setProcessContext(context: ProcessContextType) {
  45. currentContext = context;
  46. }