generated from salesforcecli/plugin-template-sf
-
Notifications
You must be signed in to change notification settings - Fork 0
W-16451172 Wr/api request rest #5
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
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
4801b68
chore: move org api -> api request rest
WillieRuemmele 9dcbfa7
chore: set beta state, unhide command, bump deps
WillieRuemmele 1c3fade
chore: merge main, resolve conflicts
WillieRuemmele ae3a9fa
test: add NUT
WillieRuemmele 475d7a8
chore: add NUT debug logging
WillieRuemmele 1b5fd72
chore: bump api version?
WillieRuemmele ff57171
chore: more logging
WillieRuemmele 8362d19
chore: skip windows for now
WillieRuemmele 16c6347
chore: use os.platform
WillieRuemmele 594bd27
chore: move validation left, standard headers, util methods
WillieRuemmele 39988e1
chore: default to services/data/vXX.0
WillieRuemmele bee7ae1
chore: snapshot
WillieRuemmele cc7bc9d
chore: add exmaple, empty body message
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 hidden or 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 |
|---|---|---|
| @@ -1 +1,10 @@ | ||
| [] | ||
| [ | ||
| { | ||
| "alias": [], | ||
| "command": "api:request:rest", | ||
| "flagAliases": [], | ||
| "flagChars": ["H", "S", "X", "i", "o"], | ||
| "flags": ["api-version", "body", "flags-dir", "header", "include", "method", "stream-to-file", "target-org"], | ||
| "plugin": "@salesforce/plugin-api" | ||
| } | ||
| ] |
This file contains hidden or 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,56 @@ | ||
| # 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 %> 'limits' --target-org my-org | ||
|
|
||
| - List all endpoints | ||
|
|
||
| <%= config.bin %> <%= command.id %> '/' | ||
|
|
||
| - Get the response in XML format by specifying the "Accept" HTTP header: | ||
|
|
||
| <%= config.bin %> <%= command.id %> 'limits' --target-org my-org --header 'Accept: application/xml' | ||
|
|
||
| - POST to create an Account object | ||
|
|
||
| <%= config.bin %> <%= command.id %> 'sobjects/account' --body "{\"Name\" : \"Account from REST API\",\"ShippingCity\" : \"Boise\"}" --method POST | ||
|
|
||
| - or with a file 'info.json' containing | ||
|
|
||
| ```json | ||
| { | ||
| "Name": "Demo", | ||
| "ShippingCity": "Boise" | ||
| } | ||
| ``` | ||
|
|
||
| <%= config.bin %> <%= command.id %> 'sobjects/account' --body info.json --method POST | ||
|
|
||
| - Update object | ||
|
|
||
| <%= config.bin %> <%= command.id %> 'sobjects/account/<Account ID>' --body "{\"BillingCity\": \"San Francisco\"}" --method PATCH | ||
|
|
||
| # 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. | ||
This file contains hidden or 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 hidden or 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,146 @@ | ||
| /* | ||
| * 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, readFileSync, existsSync } from 'node:fs'; | ||
| import { join } from 'node:path'; | ||
| import got 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, SFDX_HTTP_HEADERS, SfError } from '@salesforce/core'; | ||
| import { Args } from '@oclif/core'; | ||
| import ansis from 'ansis'; | ||
| import { getHeaders } from '../../../shared/methods.js'; | ||
|
|
||
| Messages.importMessagesDirectoryFromMetaUrl(import.meta.url); | ||
| const messages = Messages.loadMessages('@salesforce/plugin-api', 'rest'); | ||
|
|
||
| export class Rest extends SfCommand<void> { | ||
| public static readonly summary = messages.getMessage('summary'); | ||
| public static readonly examples = messages.getMessages('examples'); | ||
| public static state = 'beta'; | ||
| public static enableJsonFlag = false; | ||
| public static readonly flags = { | ||
| 'target-org': Flags.requiredOrg(), | ||
| 'api-version': Flags.orgApiVersion(), | ||
| 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({ | ||
mshanemc marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| summary: messages.getMessage('flags.body.summary'), | ||
| allowStdin: true, | ||
| helpValue: 'file', | ||
| }), | ||
| }; | ||
|
|
||
| public static args = { | ||
mshanemc marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| endpoint: Args.string({ | ||
| description: 'Salesforce API endpoint', | ||
mshanemc marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| required: true, | ||
| }), | ||
| }; | ||
|
|
||
| public async run(): Promise<void> { | ||
| const { flags, args } = await this.parse(Rest); | ||
|
|
||
| const org = flags['target-org']; | ||
| const streamFile = flags['stream-to-file']; | ||
| const headers = flags.header ? getHeaders(flags.header) : {}; | ||
|
|
||
| // replace first '/' to create valid URL | ||
| const endpoint = args.endpoint.startsWith('/') ? args.endpoint.replace('/', '') : args.endpoint; | ||
| const url = new URL( | ||
| `${org.getField<string>(Org.Fields.INSTANCE_URL)}/services/data/v${ | ||
| flags['api-version'] ?? (await org.retrieveMaxApiVersion()) | ||
| }/${endpoint}` | ||
| ); | ||
|
|
||
| const body = | ||
| flags.method === 'GET' | ||
| ? undefined | ||
| : // if they've passed in a file name, check and read it | ||
| existsSync(join(process.cwd(), flags.body ?? '')) | ||
| ? readFileSync(join(process.cwd(), flags.body ?? '')) | ||
| : // otherwise it's a stdin, and we use it directly | ||
| flags.body; | ||
|
|
||
| await org.refreshAuth(); | ||
|
|
||
| const options = { | ||
| agent: { https: new ProxyAgent() }, | ||
| method: flags.method, | ||
| headers: { | ||
mshanemc marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ...SFDX_HTTP_HEADERS, | ||
| Authorization: `Bearer ${ | ||
mshanemc marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| // 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! | ||
| }`, | ||
| ...headers, | ||
| }, | ||
| body, | ||
| throwHttpErrors: false, | ||
| followRedirect: false, | ||
| }; | ||
|
|
||
| if (streamFile) { | ||
| const responseStream = got.stream(url, options); | ||
mshanemc marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| const fileStream = createWriteStream(streamFile); | ||
| responseStream.pipe(fileStream); | ||
mshanemc marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| 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) { | ||
| this.log(`HTTP/${res.httpVersion} ${res.statusCode}`); | ||
| Object.entries(res.headers).map(([header, value]) => { | ||
| this.log(`${ansis.blue.bold(header)}: ${Array.isArray(value) ? value.join(',') : value ?? '<undefined>'}`); | ||
| }); | ||
| } | ||
|
|
||
| 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 === '' ? `Server responded with an empty body, status code ${res.statusCode}` : res.body); | ||
| } | ||
|
|
||
| if (res.statusCode >= 400) { | ||
| process.exitCode = 1; | ||
| } | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or 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,25 @@ | ||
| /* | ||
| * 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 { SfError } from '@salesforce/core'; | ||
| import type { Headers } from 'got'; | ||
|
|
||
| export function 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; | ||
| } |
This file contains hidden or 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 hidden or 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,86 @@ | ||
| /* | ||
| * Copyright (c) 2020, 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 { join } from 'node:path'; | ||
| import { readFileSync } from 'node:fs'; | ||
| import * as os from 'node:os'; | ||
| import { config, expect } from 'chai'; | ||
| import { execCmd, TestSession } from '@salesforce/cli-plugins-testkit'; | ||
|
|
||
| config.truncateThreshold = 0; | ||
|
|
||
| const skipIfWindows = os.platform() === 'win32' ? describe.skip : describe; | ||
|
|
||
| // windows NUTs have been failing with | ||
| // URL No Longer Exists</span></td></tr> | ||
| // <tr><td>You have attempted to reach a URL that no longer exists on salesforce.com. <br/><br/> | ||
| // You may have reached this page after clicking on a direct link into the application. This direct link might be: <br/> | ||
| // A bookmark to a particular page, such as a report or view <br/> | ||
| // A link to a particular page in the Custom Links section of your Home Tab, or a Custom Link <br/> | ||
| // A link to a particular page in your email templates <br/><br/> | ||
| // | ||
| // seems to be related to clickjack protection - https://help.salesforce.com/s/articleView?id=000387058&type=1 | ||
| // I've confirmed the 'api request rest' command passes on windows | ||
|
|
||
| skipIfWindows('api:request:rest NUT', () => { | ||
| let testSession: TestSession; | ||
|
|
||
| before(async () => { | ||
| testSession = await TestSession.create({ | ||
| scratchOrgs: [ | ||
| { | ||
| config: 'config/project-scratch-def.json', | ||
| setDefault: true, | ||
| }, | ||
| ], | ||
| project: { gitClone: 'https://github.com/trailheadapps/dreamhouse-lwc' }, | ||
| devhubAuthStrategy: 'AUTO', | ||
| }); | ||
| }); | ||
|
|
||
| after(async () => { | ||
| await testSession?.clean(); | ||
| }); | ||
|
|
||
| describe('std out', () => { | ||
| it('get result in json format', () => { | ||
| const result = execCmd("api request rest 'limits'").shellOutput.stdout; | ||
|
|
||
| // make sure we got a JSON object back | ||
| expect(Object.keys(JSON.parse(result) as Record<string, unknown>)).to.have.length; | ||
| }); | ||
|
|
||
| it('should pass headers', () => { | ||
| const result = execCmd("api request rest 'limits' -H 'Accept: application/xml'").shellOutput.stdout; | ||
|
|
||
| // the headers will change this to xml | ||
| expect(result.startsWith('<?xml version="1.0" encoding="UTF-8"?><LimitsSnapshot>')).to.be.true; | ||
| }); | ||
| }); | ||
|
|
||
| describe('stream-to-file', () => { | ||
| it('get result in json format', () => { | ||
| const result = execCmd("api request rest 'limits' --stream-to-file out.txt").shellOutput.stdout; | ||
|
|
||
| expect(result.trim()).to.equal('File saved to out.txt'); | ||
|
|
||
| const content = readFileSync(join(testSession.project.dir, 'out.txt'), 'utf-8'); | ||
| // make sure we got a JSON object back | ||
| expect(Object.keys(JSON.parse(content) as Record<string, unknown>)).to.have.length; | ||
| }); | ||
|
|
||
| it('should pass headers', () => { | ||
| const result = execCmd("api request rest 'limits' -H 'Accept: application/xml' --stream-to-file out.txt") | ||
| .shellOutput.stdout; | ||
|
|
||
| expect(result.trim()).to.equal('File saved to out.txt'); | ||
|
|
||
| const content = readFileSync(join(testSession.project.dir, 'out.txt'), 'utf-8'); | ||
| expect(content.startsWith('<?xml version="1.0" encoding="UTF-8"?><LimitsSnapshot>')).to.be.true; | ||
| }); | ||
| }); | ||
| }); |
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.
Uh oh!
There was an error while loading. Please reload this page.