1. /**
  2. * Configures file processing parameters for batch execution with retries.
  3. *
  4. * @param {Array<object>} files An array of file objects. Each object should have a 'path' property (string)
  5. * and any other necessary metadata.
  6. * @param {object} options Configuration options.
  7. * @param {number} options.retryIntervalMs The interval (in milliseconds) between retry attempts.
  8. * @param {number} options.maxRetries The maximum number of retry attempts.
  9. * @param {function} options.processFile Function to process a single file. Takes the file object as input. Returns a promise.
  10. * @returns {Promise<Array<object>>} A promise that resolves to an array of processed files, or rejects if all files fail after retries.
  11. */
  12. async function processFilesBatch(files, options) {
  13. const { retryIntervalMs, maxRetries, processFile } = options;
  14. if (!files || !Array.isArray(files)) {
  15. throw new Error("Files must be a non-empty array.");
  16. }
  17. if (typeof retryIntervalMs !== 'number' || retryIntervalMs <= 0) {
  18. throw new Error("retryIntervalMs must be a positive number.");
  19. }
  20. if (typeof maxRetries !== 'number' || maxRetries <= 0) {
  21. throw new Error("maxRetries must be a positive number.");
  22. }
  23. if (typeof processFile !== 'function') {
  24. throw new Error("processFile must be a function.");
  25. }
  26. const processedFiles = [];
  27. for (const file of files) {
  28. let retryCount = 0;
  29. let fileProcessed = false;
  30. while (!fileProcessed && retryCount < maxRetries) {
  31. try {
  32. const result = await processFile(file); // Process the file
  33. processedFiles.push(result);
  34. fileProcessed = true;
  35. } catch (error) {
  36. retryCount++;
  37. console.log(`File ${file.path} failed. Retry attempt ${retryCount}/${maxRetries}. Error: ${error.message}`);
  38. await new Promise(resolve => setTimeout(resolve, retryIntervalMs)); // Wait before retrying
  39. }
  40. }
  41. if (!fileProcessed) {
  42. console.error(`File ${file.path} failed after ${maxRetries} retries.`);
  43. //Consider rejecting the entire batch here, depending on desired behavior.
  44. //For now, we continue with the next file.
  45. }
  46. }
  47. return processedFiles;
  48. }

Add your comment