1. /**
  2. * Teardowns processes of arrays for staging environments.
  3. * This function iterates through an array of process configurations and
  4. * executes teardown operations for each process. It's designed to be
  5. * used in staging environments to ensure resources are cleaned up properly.
  6. *
  7. * @param {Array<Object>} processes An array of process configuration objects.
  8. * Each object should contain a 'name' property
  9. * and a 'teardown' function.
  10. * @throws {Error} If the input is not an array.
  11. */
  12. function teardownProcesses(processes) {
  13. if (!Array.isArray(processes)) {
  14. throw new Error("Input must be an array of process configurations.");
  15. }
  16. for (const process of processes) {
  17. if (typeof process !== 'object' || process === null) {
  18. console.warn("Skipping invalid process configuration:", process); //Warn about invalid data
  19. continue;
  20. }
  21. if (typeof process.name !== 'string' || process.name.trim() === "") {
  22. console.warn("Skipping process due to missing or invalid name:", process);
  23. continue;
  24. }
  25. if (typeof process.teardown === 'function') {
  26. try {
  27. // Execute the teardown function for the current process.
  28. console.log(`Teardown for process "${process.name}" started.`);
  29. process.teardown(); // Call the teardown function
  30. console.log(`Teardown for process "${process.name}" completed.`);
  31. } catch (error) {
  32. console.error(`Error during teardown of process "${process.name}":`, error);
  33. }
  34. } else {
  35. console.warn(`Teardown function is missing for process "${process.name}".`);
  36. }
  37. }
  38. }
  39. // Example usage:
  40. // const processes = [
  41. // { name: "process1", teardown: () => console.log("Tearing down process 1...") },
  42. // { name: "process2", teardown: () => console.log("Tearing down process 2...") },
  43. // { name: "process3", teardown: () => { console.log("Tearing down process 3"); throw new Error("Simulated error"); } }, //Example with error
  44. // {name: "", teardown: () => console.log("Tearing down process with empty name")}, //Example with empty name
  45. // null, //Example with invalid data type
  46. // {teardown: "not a function"} //Example with invalid teardown function
  47. // ];
  48. // teardownProcesses(processes);

Add your comment