This repository has been archived by the owner on Sep 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapi.ts
149 lines (135 loc) · 4.47 KB
/
api.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import { readFile } from 'node:fs/promises';
import { EOL } from 'node:os';
import got, { Headers, Method } from 'got';
import * as chalk from 'chalk';
import { ProxyAgent } from 'proxy-agent';
import { SfCommand, Flags } from '@salesforce/sf-plugins-core';
import { SfError, Org } from '@salesforce/core';
import { Args, ux } from '@oclif/core';
export class OrgApi extends SfCommand<void> {
public static readonly summary =
'Makes an authenticated HTTP request to the Salesforce REST API and prints the response.';
public static readonly 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.';
public static readonly examples = [
{
description: 'List information about limits in your org:',
command:
"<%= config.bin %> <%= command.id %> 'services/data/v56.0/limits' --target-org my-org",
},
{
description:
'Get response in XML format by specifying the "Accept" HTTP header:',
command:
"<%= config.bin %> <%= command.id %> 'services/data/v56.0/limits' --target-org my-org --header 'Accept: application/xml'",
},
];
public static enableJsonFlag = false;
public static readonly flags = {
// FIXME: 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({
// TODO: this is already set in the org flag but getting a wrong type if not set here.
// Fix flag types in oclif.
required: true,
helpValue: 'username',
}),
include: Flags.boolean({
char: 'i',
summary: 'Include HTTP response status and headers in the output.',
default: false,
}),
method: Flags.custom<Method>({
options: [
'GET',
'POST',
'PUT',
'PATCH',
'HEAD',
'DELETE',
'OPTIONS',
'TRACE',
],
summary: 'The HTTP method for the request.',
char: 'X',
default: 'GET',
})(),
header: Flags.string({
summary: 'HTTP header in "key:value" format.',
helpValue: 'key:value',
char: 'H',
multiple: true,
}),
body: Flags.file({
summary: 'The file to use as the body for the request.',
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 split = header.split(':');
if (split.length !== 2) {
throw new SfError(`Failed to parse HTTP header: "${header}".`, '', [
'Make sure the header is in a "key:value" format, e.g. "Accept: application/json"',
]);
}
headers[split[0]] = split[1].trim();
}
return headers;
}
public async run(): Promise<void> {
const { flags, args } = await this.parse(OrgApi);
const org = flags['target-org'];
await org.refreshAuth();
const url = `${org.getField<string>(Org.Fields.INSTANCE_URL)}/${
args.endpoint
}`;
const res = await got(url, {
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 ? OrgApi.getHeaders(flags.header) : {}),
},
body:
flags.method === 'GET'
? undefined
: flags.body
? await readFile(flags.body)
: undefined,
throwHttpErrors: false,
});
// 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 += `${chalk.blue.bold(header)}: ${
res.headers[header] as string
}${EOL}`;
}
this.log(httpInfo);
}
try {
// Try to pretty-print JSON response.
ux.styledJSON(JSON.parse(res.body));
} catch (err) {
// If response body isn't JSON, just print it to stdout.
this.log(res.body);
}
if (res.statusCode >= 400) {
process.exitCode = 1;
}
}
}