@salesforce/plugin-api
Version:
A plugin to call API endpoints via CLI commands
68 lines • 2.71 kB
JavaScript
/*
* Copyright (c) 2023, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import { createWriteStream } from 'node:fs';
import { Messages, SfError } from '@salesforce/core';
import { Flags } from '@salesforce/sf-plugins-core';
import ansis from 'ansis';
import got from 'got';
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@salesforce/plugin-api', 'shared');
export async function sendAndPrintRequest(options) {
if (options.streamFile) {
const responseStream = options.options.method
? got.stream(options.url, options.options)
: // default to 'POST' if not specified
got.stream.post(options.url, options.options);
const fileStream = createWriteStream(options.streamFile);
responseStream.pipe(fileStream);
// we just ensured it existed with the 'if'
fileStream.on('finish', () => options.this.log(`File saved to ${options.streamFile}`));
fileStream.on('error', (error) => {
throw SfError.wrap(error);
});
responseStream.on('error', (error) => {
throw SfError.wrap(error);
});
}
else {
const res = options.options.method
? // default to 'POST' if not specified
await got(options.url, options.options)
: await got.post(options.url, options.options);
// Print HTTP response status and headers.
if (options.include) {
options.this.log(`HTTP/${res.httpVersion} ${res.statusCode}`);
Object.entries(res.headers).map(([header, value]) => {
options.this.log(`${ansis.blue.bold(header)}: ${Array.isArray(value) ? value.join(',') : value ?? '<undefined>'}`);
});
}
try {
// Try to pretty-print JSON response.
options.this.styledJSON(JSON.parse(res.body));
}
catch (err) {
// If response body isn't JSON, just print it to stdout.
options.this.log(res.body);
}
if (res.statusCode >= 400) {
process.exitCode = 1;
}
}
}
export const includeFlag = Flags.boolean({
char: 'i',
summary: messages.getMessage('flags.include.summary'),
default: false,
exclusive: ['stream-to-file'],
});
export const streamToFileFlag = Flags.string({
summary: messages.getMessage('flags.stream-to-file.summary'),
helpValue: 'Example: report.xlsx',
char: 'S',
exclusive: ['include'],
});
//# sourceMappingURL=shared.js.map