Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wr/org api rest #1174

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions command-snapshot.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,14 @@
"flags": ["api-version", "flags-dir", "json", "loglevel", "no-prompt", "target-org", "targetdevhubusername"],
"plugin": "@salesforce/plugin-org"
},
{
"alias": [],
"command": "org:api:rest",
"flagAliases": [],
"flagChars": ["H", "S", "X", "i", "o"],
"flags": ["body", "flags-dir", "header", "include", "method", "stream-to-file", "target-org"],
"plugin": "@salesforce/plugin-org"
},
{
"alias": ["env:create:sandbox"],
"command": "org:create:sandbox",
Expand Down
33 changes: 33 additions & 0 deletions messages/rest.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# summary

Make an authenticated HTTP request to Salesforce REST API and print the response.

# examples

- List information about limits in the org with alias "my-org":

<%= config.bin %> <%= command.id %> 'services/data/v56.0/limits' --target-org my-org

- Get the response in XML format by specifying the "Accept" HTTP header:

<%= config.bin %> <%= command.id %> 'services/data/v56.0/limits' --target-org my-org --header 'Accept: application/xml',

# flags.include.summary

Include the HTTP response status and headers in the output.

# flags.method.summary

HTTP method for the request.

# flags.header.summary

HTTP header in "key:value" format.

# flags.stream-to-file.summary

Stream responses to a file.

# flags.body.summary

File to use as the body for the request. Specify "-" to read from standard input; specify "" for an empty body.
8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,26 @@
"author": "Salesforce",
"bugs": "https://github.com/forcedotcom/cli/issues",
"dependencies": {
"@oclif/core": "^4.0.16",
"@oclif/core": "^4.0.17",
"@salesforce/core": "^8.2.7",
"@salesforce/kit": "^3.2.0",
"@salesforce/sf-plugins-core": "^11.3.0",
"@salesforce/source-deploy-retrieve": "^12.1.12",
"ansis": "^3.2.0",
"change-case": "^5.4.4",
"got": "^13.0.0",
"is-wsl": "^3.1.0",
"open": "^10.1.0"
"open": "^10.1.0",
"proxy-agent": "^6.4.0"
},
"devDependencies": {
"@oclif/plugin-command-snapshot": "^5.2.7",
"@salesforce/cli-plugins-testkit": "^5.3.25",
"@salesforce/dev-scripts": "^10.2.9",
"@salesforce/plugin-command-reference": "^3.1.15",
"@salesforce/ts-sinon": "^1.4.23",
"@types/got": "^9.6.12",
"nock": "^13.3.0",
"eslint-plugin-sf-plugin": "^1.20.1",
"moment": "^2.30.1",
"oclif": "^4.14.17",
Expand Down
151 changes: 151 additions & 0 deletions src/commands/org/api/rest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
/*
* 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 { EOL } from 'node:os';
import { createWriteStream } from 'node:fs';
import got, { Headers } from 'got';
import type { AnyJson } from '@salesforce/ts-types';
import { ProxyAgent } from 'proxy-agent';
import { Flags, SfCommand } from '@salesforce/sf-plugins-core';
import { Messages, Org, SfError } from '@salesforce/core';
import { Args } from '@oclif/core';
import ansis from 'ansis';

Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@salesforce/plugin-org', 'rest');

export class Rest extends SfCommand<void> {
public static readonly summary = messages.getMessage('summary');
public static readonly examples = messages.getMessages('examples');
public static readonly hidden = true;
public static enableJsonFlag = false;
public static readonly flags = {
// TODO: getting a false positive from this eslint rule.
// summary is already set in the org flag.
// eslint-disable-next-line sf-plugin/flag-summary
'target-org': Flags.requiredOrg({
helpValue: 'username',
}),
include: Flags.boolean({
char: 'i',
summary: messages.getMessage('flags.include.summary'),
default: false,
exclusive: ['stream-to-file'],
}),
method: Flags.option({
options: ['GET', 'POST', 'PUT', 'PATCH', 'HEAD', 'DELETE', 'OPTIONS', 'TRACE'] as const,
summary: messages.getMessage('flags.method.summary'),
char: 'X',
default: 'GET',
})(),
header: Flags.string({
summary: messages.getMessage('flags.header.summary'),
helpValue: 'key:value',
char: 'H',
multiple: true,
}),
'stream-to-file': Flags.string({
summary: messages.getMessage('flags.stream-to-file.summary'),
helpValue: 'Example: report.xlsx',
char: 'S',
exclusive: ['include'],
}),
body: Flags.string({
summary: messages.getMessage('flags.body.summary'),
allowStdin: true,
helpValue: 'file',
}),
};

public static args = {
endpoint: Args.string({
description: 'Salesforce API endpoint',
required: true,
}),
};

private static getHeaders(keyValPair: string[]): Headers {
const headers: { [key: string]: string } = {};

for (const header of keyValPair) {
const [key, ...rest] = header.split(':');
const value = rest.join(':').trim();
if (!key || !value) {
throw new SfError(`Failed to parse HTTP header: "${header}".`, 'Failed To Parse HTTP Header', [
'Make sure the header is in a "key:value" format, e.g. "Accept: application/json"',
]);
}
headers[key] = value;
}

return headers;
}

public async run(): Promise<void> {
const { flags, args } = await this.parse(Rest);

const org = flags['target-org'];
const streamFile = flags['stream-to-file'];

await org.refreshAuth();

const url = `${org.getField<string>(Org.Fields.INSTANCE_URL)}/${args.endpoint}`;

const options = {
agent: { https: new ProxyAgent() },
method: flags.method,
headers: {
Authorization: `Bearer ${
// we don't care about apiVersion here, just need to get the access token.
// eslint-disable-next-line sf-plugin/get-connection-with-version
org.getConnection().getConnectionOptions().accessToken!
}`,
...(flags.header ? Rest.getHeaders(flags.header) : {}),
},
body: flags.method === 'GET' ? undefined : flags.body,
throwHttpErrors: false,
followRedirect: false,
};

if (streamFile) {
const responseStream = got.stream(url, options);
const fileStream = createWriteStream(streamFile);
responseStream.pipe(fileStream);

fileStream.on('finish', () => this.log(`File saved to ${streamFile}`));
fileStream.on('error', (error) => {
throw SfError.wrap(error);
});
responseStream.on('error', (error) => {
throw SfError.wrap(error);
});
} else {
const res = await got(url, options);

// Print HTTP response status and headers.
if (flags.include) {
let httpInfo = `HTTP/${res.httpVersion} ${res.statusCode} ${EOL}`;

for (const [header] of Object.entries(res.headers)) {
httpInfo += `${ansis.blue.bold(header)}: ${res.headers[header] as string}${EOL}`;
}
this.log(httpInfo);
}

try {
// Try to pretty-print JSON response.
this.styledJSON(JSON.parse(res.body) as AnyJson);
} catch (err) {
// If response body isn't JSON, just print it to stdout.
this.log(res.body);
}

if (res.statusCode >= 400) {
process.exitCode = 1;
}
}
}
}
124 changes: 124 additions & 0 deletions test/unit/org/api/rest.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
/*
* 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 process from 'node:process';
import path from 'node:path';
import { SfError } from '@salesforce/core';
import { expect } from 'chai';
import stripAnsi from 'strip-ansi';
import { MockTestOrgData, TestContext } from '@salesforce/core/testSetup';
import { sleep } from '@salesforce/kit';
import nock = require('nock');
import { Rest } from '../../../../src/commands/org/api/rest.js';

describe('rest', () => {
const $$ = new TestContext();
const testOrg = new MockTestOrgData('1234', {
username: '[email protected]',
});

let stdoutSpy: sinon.SinonSpy;

const orgLimitsResponse = {
ActiveScratchOrgs: {
Max: 200,
Remaining: 199,
},
};

beforeEach(async () => {
await $$.stubAuths(testOrg);

stdoutSpy = $$.SANDBOX.stub(process.stdout, 'write');
});

afterEach(() => {
$$.SANDBOX.restore();
});

it('should request org limits and default to "GET" HTTP method', async () => {
nock(testOrg.instanceUrl).get('/services/data/v56.0/limits').reply(200, orgLimitsResponse);

await Rest.run(['services/data/v56.0/limits', '--target-org', '[email protected]']);

const output = stripAnsi(stdoutSpy.args.flat().join(''));

expect(JSON.parse(output)).to.deep.equal(orgLimitsResponse);
});

it('should redirect to file', async () => {
nock(testOrg.instanceUrl).get('/services/data/v56.0/limits').reply(200, orgLimitsResponse);

await Rest.run(['services/data/v56.0/limits', '--target-org', '[email protected]', '--stream-to-file', 'myOutput.txt']);

// gives it a second to resolve promises and close streams before we start asserting
await sleep(1000);
const output = stripAnsi(stdoutSpy.args.flat().join(''));

expect(output).to.deep.equal('File saved to myOutput.txt' + '\n');
expect(JSON.parse(fs.readFileSync('myOutput.txt', 'utf8'))).to.deep.equal(orgLimitsResponse);

after(() => {
// more than a UT
fs.rmSync(path.join(process.cwd(), 'myOutput.txt'));
});
});

it('should set "Accept" HTTP header', async () => {
const xmlRes = `<?xml version="1.0" encoding="UTF-8"?>
<LimitsSnapshot>
<ActiveScratchOrgs>
<Max>200</Max>
<Remaining>198</Remaining>
</ActiveScratchOrgs>
</LimitsSnapshot>`;

nock(testOrg.instanceUrl, {
reqheaders: {
accept: 'application/xml',
},
})
.get('/services/data')
.reply(200, xmlRes);

await Rest.run(['services/data', '--header', 'Accept: application/xml', '--target-org', '[email protected]']);

const output = stripAnsi(stdoutSpy.args.flat().join(''));

// https://github.com/oclif/core/blob/ff76400fb0bdfc4be0fa93056e86183b9205b323/src/command.ts#L248-L253
expect(output).to.equal(xmlRes + '\n');
});

it('should validate HTTP headers are in a "key:value" format', async () => {
try {
await Rest.run(['services/data', '--header', 'Accept application/xml', '--target-org', '[email protected]']);
} catch (e) {
const err = e as SfError;
expect(err.message).to.equal('Failed to parse HTTP header: "Accept application/xml".');
if (!err.actions || err.actions?.length === 0) {
expect.fail('Missing action message for invalid header error.');
}
expect(err.actions[0]).to.equal(
'Make sure the header is in a "key:value" format, e.g. "Accept: application/json"'
);
}
});

it('should not follow redirects', async () => {
nock(testOrg.instanceUrl)
.get('/services/data/v56.0/limites')
.reply(301, orgLimitsResponse, {
location: `${testOrg.instanceUrl}/services/data/v56.0/limits`,
});

await Rest.run(['services/data/v56.0/limites', '--target-org', '[email protected]']);

const output = stripAnsi(stdoutSpy.args.flat().join(''));

expect(JSON.parse(output)).to.deep.equal(orgLimitsResponse);
});
});
Loading