1. const fs = require('fs');
  2. const path = require('path');
  3. /**
  4. * Formats session cookies for data migration based on a configuration file.
  5. *
  6. * @param {string} configPath Path to the configuration file.
  7. * @returns {string} Formatted session cookie data.
  8. * @throws {Error} If the configuration file is invalid or missing.
  9. */
  10. function formatSessionCookies(configPath) {
  11. try {
  12. const config = require(path.resolve(configPath)); // Load config from path
  13. if (!config || typeof config !== 'object') {
  14. throw new Error('Invalid configuration file: Must be an object.');
  15. }
  16. const sessionCookies = config.sessionCookies;
  17. if (!sessionCookies || !Array.isArray(sessionCookies)) {
  18. throw new Error('Missing or invalid sessionCookies array in configuration.');
  19. }
  20. let formattedOutput = '';
  21. for (const cookie of sessionCookies) {
  22. const { name, value, domain, path, expiry } = cookie;
  23. //Handle missing expiry gracefully.
  24. const expiryString = expiry ? ` expires="${expiry}"` : '';
  25. formattedOutput += `name=${name},value=${value}`;
  26. if (domain) {
  27. formattedOutput += `,domain=${domain}`;
  28. }
  29. if (path) {
  30. formattedOutput += `,path=${path}`;
  31. }
  32. formattedOutput += expiryString;
  33. formattedOutput += '\n';
  34. }
  35. return formattedOutput;
  36. } catch (error) {
  37. console.error('Error formatting session cookies:', error.message);
  38. throw error; // Re-throw to allow calling function to handle the error.
  39. }
  40. }
  41. module.exports = formatSessionCookies;

Add your comment