|
| 1 | +/* |
| 2 | + * Copyright (c) 2023, salesforce.com, inc. |
| 3 | + * All rights reserved. |
| 4 | + * Licensed under the BSD 3-Clause license. |
| 5 | + * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause |
| 6 | + */ |
| 7 | +import { createWriteStream, readFileSync, existsSync } from 'node:fs'; |
| 8 | +import { join } from 'node:path'; |
| 9 | +import got from 'got'; |
| 10 | +import type { AnyJson } from '@salesforce/ts-types'; |
| 11 | +import { ProxyAgent } from 'proxy-agent'; |
| 12 | +import { Flags, SfCommand } from '@salesforce/sf-plugins-core'; |
| 13 | +import { Messages, Org, SFDX_HTTP_HEADERS, SfError } from '@salesforce/core'; |
| 14 | +import { Args } from '@oclif/core'; |
| 15 | +import ansis from 'ansis'; |
| 16 | +import { getHeaders } from '../../../shared/methods.js'; |
| 17 | + |
| 18 | +Messages.importMessagesDirectoryFromMetaUrl(import.meta.url); |
| 19 | +const messages = Messages.loadMessages('@salesforce/plugin-api', 'rest'); |
| 20 | + |
| 21 | +export class Rest extends SfCommand<void> { |
| 22 | + public static readonly summary = messages.getMessage('summary'); |
| 23 | + public static readonly examples = messages.getMessages('examples'); |
| 24 | + public static state = 'beta'; |
| 25 | + public static enableJsonFlag = false; |
| 26 | + public static readonly flags = { |
| 27 | + 'target-org': Flags.requiredOrg(), |
| 28 | + 'api-version': Flags.orgApiVersion(), |
| 29 | + include: Flags.boolean({ |
| 30 | + char: 'i', |
| 31 | + summary: messages.getMessage('flags.include.summary'), |
| 32 | + default: false, |
| 33 | + exclusive: ['stream-to-file'], |
| 34 | + }), |
| 35 | + method: Flags.option({ |
| 36 | + options: ['GET', 'POST', 'PUT', 'PATCH', 'HEAD', 'DELETE', 'OPTIONS', 'TRACE'] as const, |
| 37 | + summary: messages.getMessage('flags.method.summary'), |
| 38 | + char: 'X', |
| 39 | + default: 'GET', |
| 40 | + })(), |
| 41 | + header: Flags.string({ |
| 42 | + summary: messages.getMessage('flags.header.summary'), |
| 43 | + helpValue: 'key:value', |
| 44 | + char: 'H', |
| 45 | + multiple: true, |
| 46 | + }), |
| 47 | + 'stream-to-file': Flags.string({ |
| 48 | + summary: messages.getMessage('flags.stream-to-file.summary'), |
| 49 | + helpValue: 'Example: report.xlsx', |
| 50 | + char: 'S', |
| 51 | + exclusive: ['include'], |
| 52 | + }), |
| 53 | + body: Flags.string({ |
| 54 | + summary: messages.getMessage('flags.body.summary'), |
| 55 | + allowStdin: true, |
| 56 | + helpValue: 'file', |
| 57 | + }), |
| 58 | + }; |
| 59 | + |
| 60 | + public static args = { |
| 61 | + endpoint: Args.string({ |
| 62 | + description: 'Salesforce API endpoint', |
| 63 | + required: true, |
| 64 | + }), |
| 65 | + }; |
| 66 | + |
| 67 | + public async run(): Promise<void> { |
| 68 | + const { flags, args } = await this.parse(Rest); |
| 69 | + |
| 70 | + const org = flags['target-org']; |
| 71 | + const streamFile = flags['stream-to-file']; |
| 72 | + const headers = flags.header ? getHeaders(flags.header) : {}; |
| 73 | + |
| 74 | + // replace first '/' to create valid URL |
| 75 | + const endpoint = args.endpoint.startsWith('/') ? args.endpoint.replace('/', '') : args.endpoint; |
| 76 | + const url = new URL( |
| 77 | + `${org.getField<string>(Org.Fields.INSTANCE_URL)}/services/data/v${ |
| 78 | + flags['api-version'] ?? (await org.retrieveMaxApiVersion()) |
| 79 | + }/${endpoint}` |
| 80 | + ); |
| 81 | + |
| 82 | + const body = |
| 83 | + flags.method === 'GET' |
| 84 | + ? undefined |
| 85 | + : // if they've passed in a file name, check and read it |
| 86 | + existsSync(join(process.cwd(), flags.body ?? '')) |
| 87 | + ? readFileSync(join(process.cwd(), flags.body ?? '')) |
| 88 | + : // otherwise it's a stdin, and we use it directly |
| 89 | + flags.body; |
| 90 | + |
| 91 | + await org.refreshAuth(); |
| 92 | + |
| 93 | + const options = { |
| 94 | + agent: { https: new ProxyAgent() }, |
| 95 | + method: flags.method, |
| 96 | + headers: { |
| 97 | + ...SFDX_HTTP_HEADERS, |
| 98 | + Authorization: `Bearer ${ |
| 99 | + // we don't care about apiVersion here, just need to get the access token. |
| 100 | + // eslint-disable-next-line sf-plugin/get-connection-with-version |
| 101 | + org.getConnection().getConnectionOptions().accessToken! |
| 102 | + }`, |
| 103 | + ...headers, |
| 104 | + }, |
| 105 | + body, |
| 106 | + throwHttpErrors: false, |
| 107 | + followRedirect: false, |
| 108 | + }; |
| 109 | + |
| 110 | + if (streamFile) { |
| 111 | + const responseStream = got.stream(url, options); |
| 112 | + const fileStream = createWriteStream(streamFile); |
| 113 | + responseStream.pipe(fileStream); |
| 114 | + |
| 115 | + fileStream.on('finish', () => this.log(`File saved to ${streamFile}`)); |
| 116 | + fileStream.on('error', (error) => { |
| 117 | + throw SfError.wrap(error); |
| 118 | + }); |
| 119 | + responseStream.on('error', (error) => { |
| 120 | + throw SfError.wrap(error); |
| 121 | + }); |
| 122 | + } else { |
| 123 | + const res = await got(url, options); |
| 124 | + |
| 125 | + // Print HTTP response status and headers. |
| 126 | + if (flags.include) { |
| 127 | + this.log(`HTTP/${res.httpVersion} ${res.statusCode}`); |
| 128 | + Object.entries(res.headers).map(([header, value]) => { |
| 129 | + this.log(`${ansis.blue.bold(header)}: ${Array.isArray(value) ? value.join(',') : value ?? '<undefined>'}`); |
| 130 | + }); |
| 131 | + } |
| 132 | + |
| 133 | + try { |
| 134 | + // Try to pretty-print JSON response. |
| 135 | + this.styledJSON(JSON.parse(res.body) as AnyJson); |
| 136 | + } catch (err) { |
| 137 | + // If response body isn't JSON, just print it to stdout. |
| 138 | + this.log(res.body === '' ? `Server responded with an empty body, status code ${res.statusCode}` : res.body); |
| 139 | + } |
| 140 | + |
| 141 | + if (res.statusCode >= 400) { |
| 142 | + process.exitCode = 1; |
| 143 | + } |
| 144 | + } |
| 145 | + } |
| 146 | +} |
0 commit comments