1. const fs = require('fs');
  2. const path = require('path');
  3. const axios = require('axios');
  4. const { promisify } = require('util');
  5. const setTimeoutPromise = promisify(setTimeout);
  6. /**
  7. * Backs up API payloads with a timeout.
  8. * @param {string} apiUrl The URL of the API endpoint.
  9. * @param {string} backupDir The directory to store the backup files.
  10. * @param {number} timeoutMs The timeout in milliseconds.
  11. * @param {string} filenamePrefix Optional prefix for backup filenames.
  12. */
  13. async function backupApiPayload(apiUrl, backupDir, timeoutMs, filenamePrefix = 'api_payload') {
  14. try {
  15. // Ensure backup directory exists
  16. if (!fs.existsSync(backupDir)) {
  17. fs.mkdirSync(backupDir, { recursive: true });
  18. }
  19. const filename = `${filenamePrefix}_${Date.now()}.json`;
  20. const filePath = path.join(backupDir, filename);
  21. const timeout = setTimeout(() => {
  22. throw new Error('API request timed out');
  23. }, timeoutMs);
  24. const response = await axios.get(apiUrl, { timeout: timeoutMs });
  25. clearTimeout(timeout); // Clear timeout if request completes before timeout
  26. fs.writeFileSync(filePath, JSON.stringify(response.data, null, 2));
  27. console.log(`Backup created: ${filePath}`);
  28. } catch (error) {
  29. console.error(`Error backing up API payload from ${apiUrl}: ${error.message}`);
  30. }
  31. }
  32. module.exports = backupApiPayload;

Add your comment