1. const fs = require('fs');
  2. const path = require('path');
  3. /**
  4. * Decodes dataset input based on a configuration file.
  5. * @param {string} inputData The raw dataset input.
  6. * @param {string} configPath The path to the configuration file.
  7. * @returns {any} The decoded dataset, or null if decoding fails.
  8. */
  9. function decodeDataset(inputData, configPath) {
  10. try {
  11. // Read the configuration file.
  12. const config = require(path.resolve(configPath));
  13. // Validate configuration
  14. if (!config || typeof config.schema !== 'object' || !config.schema.type) {
  15. console.error("Invalid configuration file format.");
  16. return null;
  17. }
  18. const schemaType = config.schema.type;
  19. switch (schemaType) {
  20. case 'json':
  21. try {
  22. return JSON.parse(inputData);
  23. } catch (error) {
  24. console.error("JSON parsing error:", error);
  25. return null;
  26. }
  27. case 'csv':
  28. try {
  29. const lines = inputData.split('\n');
  30. const headers = lines[0].split(',');
  31. const data = [];
  32. for (let i = 1; i < lines.length; i++) {
  33. const values = lines[i].split(',');
  34. if (values.length !== headers.length) {
  35. console.warn(`Skipping row ${i + 1} due to mismatched column count.`);
  36. continue;
  37. }
  38. const row = {};
  39. for (let j = 0; j < headers.length; j++) {
  40. row[headers[j].trim()] = values[j].trim();
  41. }
  42. data.push(row);
  43. }
  44. return data;
  45. } catch (error) {
  46. console.error("CSV parsing error:", error);
  47. return null;
  48. }
  49. case 'yaml':
  50. try {
  51. return require('yaml').parse(inputData);
  52. } catch (error) {
  53. console.error("YAML parsing error:", error);
  54. return null;
  55. }
  56. default:
  57. console.error("Unsupported schema type:", schemaType);
  58. return null;
  59. }
  60. } catch (error) {
  61. console.error("Error during decoding:", error);
  62. return null;
  63. }
  64. }
  65. module.exports = decodeDataset;

Add your comment