|
| 1 | +import '@pkerschbaum/runtime-extensions-node'; |
| 2 | + |
| 3 | +import * as commander from '@commander-js/extra-typings'; |
| 4 | +import fs from 'node:fs'; |
| 5 | +import stream from 'node:stream'; |
| 6 | + |
| 7 | +import { fetchCommand } from '#pkg/commands/fetch.js'; |
| 8 | +import type { CommandResult } from '#pkg/types.js'; |
| 9 | + |
| 10 | +const outputTypes = ['console', 'file'] as const; |
| 11 | +type OutputType = (typeof outputTypes)[number]; |
| 12 | + |
| 13 | +const runCommand = new commander.Command('fetch') |
| 14 | + .addOption( |
| 15 | + new commander.Option('--output <output-type>') |
| 16 | + .choices(outputTypes) |
| 17 | + .makeOptionMandatory() |
| 18 | + .default('console'), |
| 19 | + ) |
| 20 | + .addOption(new commander.Option('--include-body')) |
| 21 | + .addArgument(new commander.Argument('<url>')) |
| 22 | + .action(async (url, options) => { |
| 23 | + const commandResult = await fetchCommand({ url, includeBody: options.includeBody }); |
| 24 | + await outputTypeToPrintFn[options.output](commandResult); |
| 25 | + }); |
| 26 | + |
| 27 | +const program = new commander.Command().addCommand(runCommand); |
| 28 | +program.parse(); |
| 29 | + |
| 30 | +const outputTypeToPrintFn: Record< |
| 31 | + OutputType, |
| 32 | + (commandResults: CommandResult[]) => void | Promise<void> |
| 33 | +> = { |
| 34 | + console: async (commandResults) => { |
| 35 | + for (const result of commandResults) { |
| 36 | + console.log(`\n--- Output for ${result.name} ---`); |
| 37 | + try { |
| 38 | + for await (const chunk of result.output) { |
| 39 | + process.stdout.write(chunk); |
| 40 | + } |
| 41 | + } catch (error) { |
| 42 | + console.error(`Error reading stream for ${result.name}:`, error); |
| 43 | + } |
| 44 | + process.stdout.write('\n'); |
| 45 | + } |
| 46 | + }, |
| 47 | + file: async (commandResults) => { |
| 48 | + const timestamp = new Date().toISOString().replace(/[-:.]/g, ''); |
| 49 | + for (const [index, result] of commandResults.entries()) { |
| 50 | + const filePath = `./${timestamp}-${index + 1}-${result.name}.txt`; |
| 51 | + const fileStream = fs.createWriteStream(filePath, { encoding: 'utf8' }); |
| 52 | + try { |
| 53 | + await stream.promises.pipeline(result.output, fileStream); |
| 54 | + } catch (error) { |
| 55 | + console.error(`Error writing file ${filePath}:`, error); |
| 56 | + // Clean up partially written file on error |
| 57 | + try { |
| 58 | + await fs.promises.unlink(filePath); |
| 59 | + } catch { |
| 60 | + // ignore |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + }, |
| 65 | +}; |
0 commit comments