@qodalis/cli-curl
Version:
Provide utility functions for the library curl
245 lines (238 loc) • 10.1 kB
JavaScript
import * as i0 from '@angular/core';
import { Injectable, NgModule } from '@angular/core';
import { resolveCommandProcessorProvider } from '@qodalis/angular-cli';
import { DefaultLibraryAuthor } from '@qodalis/cli-core';
// Automatically generated during build
const LIBRARY_VERSION = '0.0.2';
class CliCurlCommandProcessor {
constructor() {
this.command = 'curl';
this.description = 'A command-line tool to execute HTTP requests on your server. Supports GET, POST, PUT, DELETE, headers, and body data.';
this.author = DefaultLibraryAuthor;
this.version = LIBRARY_VERSION;
this.processors = [];
this.metadata = {
icon: '🌐',
};
this.registerSubProcessors();
}
async processCommand(command, context) {
context.executor.showHelp(command, context);
}
async initialize(context) { }
registerSubProcessors() {
this.processors = [
{
command: 'get',
description: 'Perform an HTTP GET request',
valueRequired: true,
parameters: [
{
name: 'header',
aliases: ['H'],
type: 'array',
description: 'Add custom headers. Accept multiple headers.',
required: false,
},
{
name: 'proxy',
type: 'boolean',
description: 'Use procy',
required: false,
},
],
processCommand: async (command, context) => {
await this.executeRequest('GET', command, context);
},
},
{
command: 'post',
description: 'Perform an HTTP POST request',
valueRequired: true,
parameters: [
{
name: 'header',
aliases: ['H'],
type: 'array',
description: 'Add custom headers',
required: false,
},
{
name: 'data',
aliases: ['d'],
type: 'string',
description: 'Request body',
required: false,
},
{
name: 'proxy',
type: 'boolean',
description: 'Use procy',
required: false,
},
],
processCommand: async (command, context) => {
await this.executeRequest('POST', command, context);
},
},
{
command: 'put',
description: 'Perform an HTTP PUT request',
valueRequired: true,
parameters: [
{
name: 'header',
aliases: ['H'],
type: 'array',
description: 'Add custom headers',
required: false,
},
{
name: 'data',
aliases: ['d'],
type: 'string',
description: 'Request body',
required: false,
},
{
name: 'proxy',
type: 'boolean',
description: 'Use procy',
required: false,
},
],
processCommand: async (command, context) => {
await this.executeRequest('PUT', command, context);
},
},
{
command: 'delete',
description: 'Perform an HTTP DELETE request',
valueRequired: true,
parameters: [
{
name: 'header',
aliases: ['H'],
type: 'array',
description: 'Add custom headers',
required: false,
},
{
name: 'proxy',
type: 'boolean',
description: 'Use procy',
required: false,
},
],
processCommand: async (command, context) => {
await this.executeRequest('DELETE', command, context);
},
},
];
}
async executeRequest(method, command, context) {
const url = command.value;
const headers = command.args['header'] || command.args['H'] || [];
const data = command.args['data'] || command.args['d'];
const verbose = !!command.args['verbose'];
const useProxy = !!command.args['proxy'];
if (!url) {
context.writer.writeError('URL is required.');
return;
}
// Prepare headers
const headersObject = headers.reduce((acc, header) => {
const [key, value] = header.split(':').map((str) => str.trim());
if (key && value)
acc[key] = value;
return acc;
}, {});
// Prepare request options
const options = {
method,
headers: headersObject,
body: data ? JSON.stringify(JSON.parse(data)) : undefined,
};
try {
const requestUrl = useProxy ? this.rewriteUrlToProxy(url) : url;
const response = await fetch(requestUrl, options);
const text = await response.text();
context.writer.writeSuccess('Request successful:');
if (verbose) {
context.writer.writeln(`Status: ${response.status}`);
context.writer.writeln(`Headers: ${JSON.stringify(response.headers, null, 2)}`);
}
context.writer.writeln(text);
context.process.output(text);
}
catch (error) {
context.writer.writeError(`Request failed: ${error}`);
context.process.exit(-1);
}
finally {
context.writer.writeln();
context.writer.writeInfo('Equivalent curl command:');
context.writer.writeln(this.generateCurlCommand(url, method, headers, data));
}
}
generateCurlCommand(url, method, headers, data) {
const headerString = headers.map((h) => `-H "${h}"`).join(' ');
const dataString = data ? `-d '${data}'` : '';
return `curl -X ${method} ${headerString} ${dataString} "${url}"`;
}
rewriteUrlToProxy(originalUrl) {
const regex = /^(https?):\/\/([^\/]+)(\/.*)?$/i;
const match = originalUrl.match(regex);
if (!match) {
throw new Error('Invalid URL provided');
}
const scheme = match[1]; // 'http' or 'https'
const domain = match[2]; // domain.com
const path = match[3] || '/'; // /path or '/'
return `https://proxy.qodalis.com/proxy/${scheme}/${domain}${path}`;
}
writeDescription(context) {
context.writer.writeln(this.description);
context.writer.writeln();
context.writer.writeln('Usage:');
context.writer.writeln(' curl <method> <url> [options]');
context.writer.writeln();
context.writer.writeln('Options:');
context.writer.writeln(' -H, --header Add custom headers (e.g., -H="Authorization: Bearer <token>")');
context.writer.writeln(' -d, --data Add request body');
context.writer.writeln(' --verbose Print detailed response');
context.writer.writeln();
context.writer.writeln('Examples:');
context.writer.writeln(' curl get https://api.example.com/users');
context.writer.writeln(' curl post https://api.example.com/users -d=\'{"name":"John"}\' -H="Content-Type: application/json"');
context.writer.writeln();
context.writer.writeWarning('Note: The server must allow CORS for this tool to work.');
}
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.12", ngImport: i0, type: CliCurlCommandProcessor, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.2.12", ngImport: i0, type: CliCurlCommandProcessor }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.12", ngImport: i0, type: CliCurlCommandProcessor, decorators: [{
type: Injectable
}], ctorParameters: function () { return []; } });
class CliCurlModule {
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.12", ngImport: i0, type: CliCurlModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "16.2.12", ngImport: i0, type: CliCurlModule }); }
static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "16.2.12", ngImport: i0, type: CliCurlModule, providers: [resolveCommandProcessorProvider(CliCurlCommandProcessor)] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.12", ngImport: i0, type: CliCurlModule, decorators: [{
type: NgModule,
args: [{
declarations: [],
imports: [],
exports: [],
providers: [resolveCommandProcessorProvider(CliCurlCommandProcessor)],
}]
}] });
/*
* Public API Surface of string
*/
/**
* Generated bundle index. Do not edit.
*/
export { CliCurlCommandProcessor, CliCurlModule };
//# sourceMappingURL=qodalis-cli-curl.mjs.map