1. #!/usr/bin/env node
  2. const { program } = require('commander');
  3. const axios = require('axios');
  4. const fs = require('fs/promises');
  5. const path = require('path');
  6. program
  7. .version('1.0.0')
  8. .description('CLI for batch processing API endpoints');
  9. program
  10. .command('process')
  11. .description('Process a batch file')
  12. .option('-f, --file <file>', 'Path to the batch file')
  13. .option('-u, --url <url>', 'API endpoint URL')
  14. .option('-d, --data <data>', 'Data to send in the request body (JSON string)')
  15. .action(async (options) => {
  16. const { file, url, data } = options;
  17. if (!file) {
  18. console.error('Error: --file is required');
  19. program.help();
  20. return;
  21. }
  22. try {
  23. const batchData = await fs.readFile(file, 'utf8');
  24. const batchItems = JSON.parse(batchData);
  25. if (!Array.isArray(batchItems)) {
  26. console.error('Error: Batch file must contain a JSON array');
  27. return;
  28. }
  29. for (const item of batchItems) {
  30. try {
  31. const response = await axios.post(url, item, {
  32. headers: {
  33. 'Content-Type': 'application/json',
  34. },
  35. });
  36. console.log(`Processed item: ${item}. Status: ${response.status}`);
  37. } catch (error) {
  38. console.error(`Error processing item: ${item}. Error: ${error.message}`);
  39. }
  40. }
  41. } catch (error) {
  42. console.error(`Error reading or parsing batch file: ${error.message}`);
  43. }
  44. });
  45. program.parse(process.argv);

Add your comment