-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathapirequest.ts
405 lines (369 loc) · 13.4 KB
/
apirequest.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
// Copyright 2020 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {GaxiosPromise, Headers} from 'gaxios';
import {DefaultTransporter, OAuth2Client} from 'google-auth-library';
import * as qs from 'qs';
import * as stream from 'stream';
import * as urlTemplate from 'url-template';
import * as uuid from 'uuid';
import * as extend from 'extend';
import {APIRequestParams, BodyResponseCallback} from './api';
import {isBrowser} from './isbrowser';
import {SchemaParameters, SchemaMethod} from './schema';
import * as h2 from './http2';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const pkg = require('../../package.json');
interface Multipart {
'content-type': string;
body: string | stream.Readable;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function isReadableStream(obj: any) {
return (
obj !== null &&
typeof obj === 'object' &&
typeof obj.pipe === 'function' &&
obj.readable !== false &&
typeof obj._read === 'function' &&
typeof obj._readableState === 'object'
);
}
function getMissingParams(params: SchemaParameters, required: string[]) {
const missing = new Array<string>();
required.forEach(param => {
// Is the required param in the params object?
if (params[param] === undefined) {
missing.push(param);
}
});
// If there are any required params missing, return their names in array,
// otherwise return null
return missing.length > 0 ? missing : null;
}
/**
* Create and send request to Google API
* @param parameters Parameters used to form request
* @param callback Callback when request finished or error found
*/
export function createAPIRequest<T>(
parameters: APIRequestParams
): GaxiosPromise<T>;
export function createAPIRequest<T>(
parameters: APIRequestParams,
callback: BodyResponseCallback<T>
): void;
export function createAPIRequest<T>(
parameters: APIRequestParams,
callback?: BodyResponseCallback<T>
): void | GaxiosPromise<T> {
if (callback) {
createAPIRequestAsync<T>(parameters).then(r => callback(null, r), callback);
} else {
return createAPIRequestAsync(parameters);
}
}
async function createAPIRequestAsync<T>(parameters: APIRequestParams) {
// Combine the GaxiosOptions options passed with this specific
// API call with the global options configured at the API Context
// level, or at the global level.
const options = extend(
true,
{}, // Ensure we don't leak settings upstream
parameters.context.google?._options || {}, // Google level options
parameters.context._options || {}, // Per-API options
parameters.options // API call params
);
const params = extend(
true,
{}, // New base object
options.params, // Combined global/per-api params
parameters.params // API call params
);
options.userAgentDirectives = options.userAgentDirectives || [];
const media = params.media || {};
/**
* In a previous version of this API, the request body was stuffed in a field
* named `resource`. This caused lots of problems, because it's not uncommon
* to have an actual named parameter required which is also named `resource`.
* This meant that users would have to use `resource_` in those cases, which
* pretty much nobody figures out on their own. The request body is now
* documented as being in the `requestBody` property, but we also need to keep
* using `resource` for reasons of back-compat. Cases that need to be covered
* here:
* - user provides just a `resource` with a request body
* - user provides both a `resource` and a `resource_`
* - user provides just a `requestBody`
* - user provides both a `requestBody` and a `resource`
*/
let resource = params.requestBody;
if (
!params.requestBody &&
params.resource &&
(!parameters.requiredParams.includes('resource') ||
typeof params.resource !== 'string')
) {
resource = params.resource;
delete params.resource;
}
delete params.requestBody;
let authClient = params.auth || options.auth;
const defaultMime =
typeof media.body === 'string' ? 'text/plain' : 'application/octet-stream';
delete params.media;
delete params.auth;
// Grab headers from user provided options
const headers = params.headers || {};
populateAPIHeader(headers, options.apiVersion);
delete params.headers;
// Un-alias parameters that were modified due to conflicts with reserved names
Object.keys(params).forEach(key => {
if (key.slice(-1) === '_') {
const newKey = key.slice(0, -1);
params[newKey] = params[key];
delete params[key];
}
});
// Check for missing required parameters in the API request
const missingParams = getMissingParams(params, parameters.requiredParams);
if (missingParams) {
// Some params are missing - stop further operations and inform the
// developer which required params are not included in the request
throw new Error('Missing required parameters: ' + missingParams.join(', '));
}
// Parse urls
if (options.url) {
let url = options.url;
if (typeof url === 'object') {
url = url.toString();
}
options.url = urlTemplate.parse(url).expand(params);
}
if (parameters.mediaUrl) {
parameters.mediaUrl = urlTemplate.parse(parameters.mediaUrl).expand(params);
}
// Rewrite url if rootUrl is globally set
if (
parameters.context._options.rootUrl !== undefined &&
options.url !== undefined
) {
const originalUrl = new URL(options.url);
const path = originalUrl.href.substr(originalUrl.origin.length);
options.url = new URL(path, parameters.context._options.rootUrl).href;
}
// When forming the querystring, override the serializer so that array
// values are serialized like this:
// myParams: ['one', 'two'] ---> 'myParams=one&myParams=two'
// This serializer also encodes spaces in the querystring as `%20`,
// whereas the default serializer in gaxios encodes to a `+`.
options.paramsSerializer = params => {
return qs.stringify(params, {arrayFormat: 'repeat'});
};
// delete path params from the params object so they do not end up in query
parameters.pathParams.forEach(param => delete params[param]);
// if authClient is actually a string, use it as an API KEY
if (typeof authClient === 'string') {
params.key = params.key || authClient;
authClient = undefined;
}
function multipartUpload(multipart: Multipart[]) {
const boundary = uuid.v4();
const finale = `--${boundary}--`;
const rStream = new stream.PassThrough({
flush(callback) {
this.push('\r\n');
this.push(finale);
callback();
},
});
const pStream = new ProgressStream();
const isStream = isReadableStream(multipart[1].body);
headers['content-type'] = `multipart/related; boundary=${boundary}`;
for (const part of multipart) {
const preamble = `--${boundary}\r\ncontent-type: ${part['content-type']}\r\n\r\n`;
rStream.push(preamble);
if (typeof part.body === 'string') {
rStream.push(part.body);
rStream.push('\r\n');
} else {
// Gaxios does not natively support onUploadProgress in node.js.
// Pipe through the pStream first to read the number of bytes read
// for the purpose of tracking progress.
pStream.on('progress', bytesRead => {
if (options.onUploadProgress) {
options.onUploadProgress({bytesRead});
}
});
part.body.pipe(pStream).pipe(rStream);
}
}
if (!isStream) {
rStream.push(finale);
rStream.push(null);
}
options.data = rStream;
}
function browserMultipartUpload(multipart: Multipart[]) {
const boundary = uuid.v4();
const finale = `--${boundary}--`;
headers['content-type'] = `multipart/related; boundary=${boundary}`;
let content = '';
for (const part of multipart) {
const preamble = `--${boundary}\r\ncontent-type: ${part['content-type']}\r\n\r\n`;
content += preamble;
if (typeof part.body === 'string') {
content += part.body;
content += '\r\n';
}
}
content += finale;
options.data = content;
}
if (parameters.mediaUrl && media.body) {
options.url = parameters.mediaUrl;
if (resource) {
params.uploadType = 'multipart';
const multipart = [
{'content-type': 'application/json', body: JSON.stringify(resource)},
{
'content-type':
media.mimeType || (resource && resource.mimeType) || defaultMime,
body: media.body,
},
];
if (!isBrowser()) {
// gaxios doesn't support multipart/related uploads, so it has to
// be implemented here.
multipartUpload(multipart);
} else {
browserMultipartUpload(multipart);
}
} else {
params.uploadType = 'media';
Object.assign(headers, {'content-type': media.mimeType || defaultMime});
options.data = media.body;
}
} else {
options.data = resource || undefined;
}
options.headers = extend(true, options.headers || {}, headers);
options.params = params;
if (!isBrowser()) {
options.headers!['Accept-Encoding'] = 'gzip';
options.userAgentDirectives.push({
product: 'google-api-nodejs-client',
version: pkg.version,
comment: 'gzip',
});
const userAgent = options.userAgentDirectives
.map(d => {
let line = `${d.product}/${d.version}`;
if (d.comment) {
line += ` (${d.comment})`;
}
return line;
})
.join(' ');
options.headers!['User-Agent'] = userAgent;
}
// By default gaxios treats any 2xx as valid, and all non 2xx status
// codes as errors. This is a problem for HTTP 304s when used along
// with an eTag.
if (!options.validateStatus) {
options.validateStatus = status => {
return (status >= 200 && status < 300) || status === 304;
};
}
// Retry by default
options.retry = options.retry === undefined ? true : options.retry;
delete options.auth; // is overridden by our auth code
// Determine TPC universe
if (
options.universeDomain &&
options.universe_domain &&
options.universeDomain !== options.universe_domain
) {
throw new Error(
'Please set either universe_domain or universeDomain, but not both.'
);
}
const universeDomainEnvVar =
typeof process === 'object' && typeof process.env === 'object'
? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']
: undefined;
const universeDomain =
options.universeDomain ??
options.universe_domain ??
universeDomainEnvVar ??
'googleapis.com';
// Update URL to point to the given TPC universe
if (universeDomain !== 'googleapis.com' && options.url) {
const url = new URL(options.url);
if (url.hostname.endsWith('.googleapis.com')) {
url.hostname = url.hostname.replace(/googleapis\.com$/, universeDomain);
options.url = url.toString();
}
}
// Perform the HTTP request. NOTE: this function used to return a
// mikeal/request object. Since the transition to Axios, the method is
// now void. This may be a source of confusion for users upgrading from
// version 24.0 -> 25.0 or up.
if (authClient && typeof authClient === 'object') {
// Validate TPC universe
const universeFromAuth =
typeof authClient.getUniverseDomain === 'function'
? await authClient.getUniverseDomain()
: undefined;
if (universeFromAuth && universeDomain !== universeFromAuth) {
throw new Error(
`The configured universe domain (${universeDomain}) does not match the universe domain found in the credentials (${universeFromAuth}). ` +
"If you haven't configured the universe domain explicitly, googleapis.com is the default."
);
}
if (options.http2) {
const authHeaders = await authClient.getRequestHeaders(options.url);
const mooOpts = Object.assign({}, options);
mooOpts.headers = Object.assign(mooOpts.headers!, authHeaders);
return h2.request<T>(mooOpts);
} else {
return (authClient as OAuth2Client).request<T>(options);
}
} else {
return new DefaultTransporter().request<T>(options);
}
}
/**
* Basic Passthrough Stream that records the number of bytes read
* every time the cursor is moved.
*/
class ProgressStream extends stream.Transform {
bytesRead = 0;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
_transform(chunk: any, encoding: string, callback: Function) {
this.bytesRead += chunk.length;
this.emit('progress', this.bytesRead);
this.push(chunk);
callback();
}
}
function populateAPIHeader(headers: Headers, apiVersion: string | undefined) {
// TODO: we should eventually think about adding browser support for this
// populating the gl-web header (web support should also be added to
// google-auth-library-nodejs).
if (!isBrowser()) {
headers['x-goog-api-client'] =
`gdcl/${pkg.version} gl-node/${process.versions.node}`;
}
if (apiVersion) {
headers['x-goog-api-version'] = apiVersion;
}
}