utils.ts 1003 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { Logger } from "pino";
  2. import dotenv from 'dotenv';
  3. dotenv.config();
  4. /**
  5. * Runs the function `fn`
  6. * and retries automatically if it fails.
  7. *
  8. * Tries max `1 + retries` times
  9. * with `retryIntervalMs` milliseconds between retries.
  10. *
  11. * From https://mtsknn.fi/blog/js-retry-on-fail/
  12. */
  13. export const retry = async <T>(
  14. fn: () => Promise<T> | T,
  15. { retries, retryIntervalMs }: { retries: number; retryIntervalMs: number },
  16. ): Promise<T> => {
  17. try {
  18. return await fn();
  19. } catch (error) {
  20. if (retries <= 0) {
  21. throw error;
  22. }
  23. await sleep(retryIntervalMs);
  24. return retry(fn, { retries: retries - 1, retryIntervalMs });
  25. }
  26. };
  27. export const sleep = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms));
  28. export const retrieveEnvVariable = (variableName: string, logger: Logger) => {
  29. const variable = process.env[variableName] || '';
  30. if (!variable) {
  31. logger.error(`${variableName} is not set`);
  32. process.exit(1);
  33. }
  34. return variable;
  35. }