@salesforce/plugin-api
Version:
A plugin to call API endpoints via CLI commands
57 lines • 2.6 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 fs from 'node:fs';
import * as os from 'node:os';
import { SfCommand, Flags } from '@salesforce/sf-plugins-core';
import { Messages, Org, SFDX_HTTP_HEADERS } from '@salesforce/core';
import { ProxyAgent } from 'proxy-agent';
import { includeFlag, sendAndPrintRequest, streamToFileFlag } from '../../../shared/shared.js';
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@salesforce/plugin-api', 'graphql');
export default class Graphql extends SfCommand {
static summary = messages.getMessage('summary');
static description = messages.getMessage('description');
static examples = messages.getMessages('examples');
static state = 'beta';
static flags = {
'target-org': Flags.requiredOrg(),
'api-version': Flags.orgApiVersion(),
'stream-to-file': streamToFileFlag,
include: includeFlag,
body: Flags.string({
summary: messages.getMessage('flags.body.summary'),
allowStdin: true,
helpValue: 'file',
required: true,
}),
};
async run() {
const { flags } = await this.parse(Graphql);
const org = flags['target-org'];
const streamFile = flags['stream-to-file'];
const apiVersion = flags['api-version'] ?? (await org.retrieveMaxApiVersion());
const body = `{"query":"${(fs.existsSync(flags.body) ? fs.readFileSync(flags.body, 'utf8') : flags.body)
.replaceAll(os.EOL, '\\n')
.replaceAll('"', '\\"')}"}`;
const url = new URL(`${org.getField(Org.Fields.INSTANCE_URL)}/services/data/v${apiVersion}/graphql`);
// refresh access token to ensure `got` gets a valid access token.
// TODO: we could skip this step if we used jsforce's HTTP module instead (handles expired tokens).
await org.refreshAuth();
const options = {
agent: { https: new ProxyAgent() },
headers: {
...SFDX_HTTP_HEADERS,
Authorization: `Bearer ${org.getConnection(apiVersion).getConnectionOptions().accessToken}`,
},
body,
throwHttpErrors: false,
followRedirect: false,
};
await sendAndPrintRequest({ streamFile, url, options, include: flags.include, this: this });
}
}
//# sourceMappingURL=graphql.js.map