generated from salesforcecli/plugin-template
-
Notifications
You must be signed in to change notification settings - Fork 13
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
Closed
Wr/org api rest #1174
Changes from 3 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
123d549
feat: add org api rest
WillieRuemmele ca1b620
test: add UT
WillieRuemmele 8f52788
chore: snapshot, UT
WillieRuemmele d74d7a8
fix: edit messages
jshackell-sfdc 2a36ce1
fix: remove command description
jshackell-sfdc 08872b2
Merge pull request #1175 from salesforcecli/js/edit-messages-org-api-…
WillieRuemmele ecb4a1e
chore: use got 13 to support node 18
WillieRuemmele File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
# summary | ||
|
||
Makes an authenticated HTTP request to the Salesforce REST API and prints the response. | ||
|
||
# description | ||
|
||
You must specify a Salesforce org to use, either with the --target-org flag or by setting your default org with | ||
the `target-org` configuration variable. | ||
|
||
# examples | ||
|
||
- List information about limits in your org <%= config.bin %> <%= command.id %> 'services/data/v56.0/limits' | ||
--target-org my-org | ||
- Get 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 HTTP response status and headers in the output. | ||
|
||
# flags.method.summary | ||
|
||
The HTTP method for the request. | ||
|
||
# flags.header.summary | ||
|
||
HTTP header in "key:value" format. | ||
|
||
# flags.stream-to-file.summary | ||
|
||
Stream responses to file. | ||
|
||
# flags.body.summary | ||
|
||
The file to use as the body for the request (use "-" to read from standard input, use "" for an empty body). |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,152 @@ | ||
/* | ||
* 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 description = messages.getMessage('description'); | ||
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; | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}); | ||
}); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do we need this sentence? I assume --target-org will be a required flag? We don't explicitly say this in the command description for other commands that require an org, such as "project deploy start".