/ src / commands / api.ts
api.ts
 1  import { Command } from 'commander';
 2  import { request } from '../http.js';
 3  
 4  export function apiCommand(): Command {
 5    const api = new Command('api')
 6      .description('Make authenticated API requests')
 7      .argument('<endpoint>', 'API endpoint path (e.g., /api/v1/user)')
 8      .option('-X, --method <method>', 'HTTP method', 'GET')
 9      .option('-d, --data <json>', 'JSON data for POST/PATCH/PUT')
10      .action(async (endpoint: string, options: { method: string; data?: string }) => {
11        try {
12          const body = options.data ? JSON.parse(options.data) : undefined;
13          const response = await request(endpoint, {
14            method: options.method,
15            body,
16          });
17  
18          const text = await response.text();
19          // eslint-disable-next-line no-console
20          console.log(text);
21        } catch (error) {
22          // eslint-disable-next-line no-console
23          console.error('API request failed:', error instanceof Error ? error.message : error);
24          process.exitCode = 1;
25        }
26      });
27  
28    return api;
29  }