generated from salesforcecli/plugin-template-sf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrest.ts
216 lines (192 loc) · 7.31 KB
/
rest.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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
/*
* 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 { readFileSync, createReadStream } from 'node:fs';
import { ProxyAgent } from 'proxy-agent';
import type { Headers } from 'got';
import { Flags, SfCommand } from '@salesforce/sf-plugins-core';
import { Messages, Org, SFDX_HTTP_HEADERS, SfError } from '@salesforce/core';
import { Args } from '@oclif/core';
import FormData from 'form-data';
import { includeFlag, sendAndPrintRequest, streamToFileFlag } from '../../../shared/shared.js';
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@salesforce/plugin-api', 'rest');
const methodOptions = ['GET', 'POST', 'PUT', 'PATCH', 'HEAD', 'DELETE', 'OPTIONS', 'TRACE'] as const;
type FileFormData = {
type: 'file';
src: string | string[];
key: string;
};
type StringFormData = {
type: 'text';
value: string;
key: string;
};
type FormDataPostmanSchema = {
mode: 'formdata';
formdata: Array<FileFormData | StringFormData>;
};
type RawPostmanSchema = {
mode: 'raw';
raw: string | Record<string, unknown>;
};
export type PostmanSchema = {
url: { raw: string } | string;
method: typeof methodOptions;
description?: string;
header: string | Array<{ key: string; value: string; disabled?: boolean; description?: string }>;
body: RawPostmanSchema | FormDataPostmanSchema;
};
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 state = 'beta';
public static enableJsonFlag = false;
public static readonly flags = {
'target-org': Flags.requiredOrg(),
include: includeFlag,
method: Flags.option({
options: methodOptions,
summary: messages.getMessage('flags.method.summary'),
char: 'X',
})(),
header: Flags.string({
summary: messages.getMessage('flags.header.summary'),
helpValue: 'key:value',
char: 'H',
multiple: true,
}),
file: Flags.file({
summary: messages.getMessage('flags.file.summary'),
description: messages.getMessage('flags.file.description'),
helpValue: 'file',
char: 'f',
exclusive: ['body'],
}),
'stream-to-file': streamToFileFlag,
body: Flags.string({
summary: messages.getMessage('flags.body.summary'),
allowStdin: true,
helpValue: 'file',
char: 'b',
}),
};
public static args = {
url: Args.string({
description: 'Salesforce API endpoint',
required: false,
}),
};
public async run(): Promise<void> {
const { flags, args } = await this.parse(Rest);
const org = flags['target-org'];
const streamFile = flags['stream-to-file'];
const fileOptions: PostmanSchema | undefined = flags.file
? (JSON.parse(readFileSync(flags.file, 'utf8')) as PostmanSchema)
: undefined;
// validate that we have a URL to hit
if (!args.url && !fileOptions?.url) {
throw new SfError("The url is required either in --file file's content or as an argument");
}
// the conditional above ensures we either have an arg or it's in the file - now we just have to find where the URL value is
const specified = args.url ?? (fileOptions?.url as { raw: string }).raw ?? fileOptions?.url;
const url = new URL(`${org.getField<string>(Org.Fields.INSTANCE_URL)}/${specified.replace(/\//y, '')}`);
// default the method to GET here to allow flags to override, but not hinder reading from files, rather than setting the default in the flag definition
const method = flags.method ?? fileOptions?.method ?? 'GET';
// @ts-expect-error users _could_ put one of these in their file without knowing it's wrong - TS is smarter than users here :)
if (!methodOptions.includes(method)) {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
throw new SfError(`"${method}" must be one of ${methodOptions.join(', ')}`);
}
// body can be undefined;
// if we have a --body @myfile.json, read the file
// if we have a --body '{"key":"value"}' use that
// else read from --file's body
let body;
if (method !== 'GET') {
if (flags.body && flags.body.startsWith('@')) {
// remove the '@' and read it
body = readFileSync(flags.body.substring(1));
} else if (flags.body) {
body = flags.body;
} else if (!flags.body) {
body = getBodyContents(fileOptions?.body);
}
}
let headers = getHeaders(flags.header ?? fileOptions?.header);
if (body instanceof FormData) {
// if it's a multi-part formdata request, those have extra headers
headers = { ...headers, ...body.getHeaders() };
}
const options = {
agent: { https: new ProxyAgent() },
method,
headers: {
...SFDX_HTTP_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!
}`,
...headers,
},
body,
throwHttpErrors: false,
followRedirect: false,
};
await org.refreshAuth();
await sendAndPrintRequest({ streamFile, url, options, include: flags.include, this: this });
}
}
export const getBodyContents = (body?: PostmanSchema['body']): string | FormData => {
if (!body?.mode) {
throw new SfError("No 'mode' found in 'body' entry", undefined, ['add "mode":"raw" | "formdata" to your body']);
}
if (body?.mode === 'raw') {
return JSON.stringify(body.raw);
} else {
// parse formdata
const form = new FormData();
body?.formdata.map((data) => {
if (data.type === 'text') {
form.append(data.key, data.value);
} else if (data.type === 'file' && typeof data.src === 'string') {
form.append(data.key, createReadStream(data.src));
} else if (Array.isArray(data.src)) {
form.append(data.key, data.src);
}
});
return form;
}
};
export function getHeaders(keyValPair: string[] | PostmanSchema['header'] | undefined): Headers {
if (!keyValPair) return {};
const headers: { [key: string]: string } = {};
if (typeof keyValPair === 'string') {
const [key, ...rest] = keyValPair.split(':');
headers[key.toLowerCase()] = rest.join(':').trim();
} else {
keyValPair.map((header) => {
if (typeof header === 'string') {
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.toLowerCase()] = value;
} else if (!header.disabled) {
if (!header.key || !header.value) {
throw new SfError(`Failed to validate header: missing key: ${header.key} or value: ${header.value}`);
}
headers[header.key.toLowerCase()] = header.value;
}
});
}
return headers;
}