UNPKG

12.3 kBTypeScriptView Raw
1/// <reference types="node" />
2import { GoogleAuth, GoogleAuthOptions } from 'google-auth-library';
3import { CredentialBody } from 'google-auth-library';
4import * as r from 'teeny-request';
5import { Duplex, DuplexOptions, Readable, Writable } from 'stream';
6import { Interceptor } from './service-object';
7export declare type ResponseBody = any;
8export interface DuplexifyOptions extends DuplexOptions {
9 autoDestroy?: boolean;
10 end?: boolean;
11}
12export interface Duplexify extends Duplex {
13 readonly destroyed: boolean;
14 setWritable(writable: Writable | false | null): void;
15 setReadable(readable: Readable | false | null): void;
16}
17export interface DuplexifyConstructor {
18 obj(writable?: Writable | false | null, readable?: Readable | false | null, options?: DuplexifyOptions): Duplexify;
19 new (writable?: Writable | false | null, readable?: Readable | false | null, options?: DuplexifyOptions): Duplexify;
20 (writable?: Writable | false | null, readable?: Readable | false | null, options?: DuplexifyOptions): Duplexify;
21}
22export interface ParsedHttpRespMessage {
23 resp: r.Response;
24 err?: ApiError;
25}
26export interface MakeAuthenticatedRequest {
27 (reqOpts: DecorateRequestOptions): Duplexify;
28 (reqOpts: DecorateRequestOptions, options?: MakeAuthenticatedRequestOptions): void | Abortable;
29 (reqOpts: DecorateRequestOptions, callback?: BodyResponseCallback): void | Abortable;
30 (reqOpts: DecorateRequestOptions, optionsOrCallback?: MakeAuthenticatedRequestOptions | BodyResponseCallback): void | Abortable | Duplexify;
31 getCredentials: (callback: (err?: Error | null, credentials?: CredentialBody) => void) => void;
32 authClient: GoogleAuth;
33}
34export interface Abortable {
35 abort(): void;
36}
37export declare type AbortableDuplex = Duplexify & Abortable;
38export interface PackageJson {
39 name: string;
40 version: string;
41}
42export interface MakeAuthenticatedRequestFactoryConfig extends GoogleAuthOptions {
43 /**
44 * Automatically retry requests if the response is related to rate limits or
45 * certain intermittent server errors. We will exponentially backoff
46 * subsequent requests by default. (default: true)
47 */
48 autoRetry?: boolean;
49 /**
50 * If true, just return the provided request options. Default: false.
51 */
52 customEndpoint?: boolean;
53 /**
54 * Account email address, required for PEM/P12 usage.
55 */
56 email?: string;
57 /**
58 * Maximum number of automatic retries attempted before returning the error.
59 * (default: 3)
60 */
61 maxRetries?: number;
62 stream?: Duplexify;
63 /**
64 * A pre-instantiated GoogleAuth client that should be used.
65 * A new will be created if this is not set.
66 */
67 authClient?: GoogleAuth;
68}
69export interface MakeAuthenticatedRequestOptions {
70 onAuthenticated: OnAuthenticatedCallback;
71}
72export interface OnAuthenticatedCallback {
73 (err: Error | null, reqOpts?: DecorateRequestOptions): void;
74}
75export interface GoogleErrorBody {
76 code: number;
77 errors?: GoogleInnerError[];
78 response: r.Response;
79 message?: string;
80}
81export interface GoogleInnerError {
82 reason?: string;
83 message?: string;
84}
85export interface MakeWritableStreamOptions {
86 /**
87 * A connection instance used to get a token with and send the request
88 * through.
89 */
90 connection?: {};
91 /**
92 * Metadata to send at the head of the request.
93 */
94 metadata?: {
95 contentType?: string;
96 };
97 /**
98 * Request object, in the format of a standard Node.js http.request() object.
99 */
100 request?: r.Options;
101 makeAuthenticatedRequest(reqOpts: r.OptionsWithUri, fnobj: {
102 onAuthenticated(err: Error | null, authenticatedReqOpts?: r.Options): void;
103 }): void;
104}
105export interface DecorateRequestOptions extends r.CoreOptions {
106 autoPaginate?: boolean;
107 autoPaginateVal?: boolean;
108 objectMode?: boolean;
109 maxRetries?: number;
110 uri: string;
111 interceptors_?: Interceptor[];
112 shouldReturnStream?: boolean;
113}
114export interface ParsedHttpResponseBody {
115 body: ResponseBody;
116 err?: Error;
117}
118/**
119 * Custom error type for API errors.
120 *
121 * @param {object} errorBody - Error object.
122 */
123export declare class ApiError extends Error {
124 code?: number;
125 errors?: GoogleInnerError[];
126 response?: r.Response;
127 constructor(errorMessage: string);
128 constructor(errorBody: GoogleErrorBody);
129 /**
130 * Pieces together an error message by combining all unique error messages
131 * returned from a single GoogleError
132 *
133 * @private
134 *
135 * @param {GoogleErrorBody} err The original error.
136 * @param {GoogleInnerError[]} [errors] Inner errors, if any.
137 * @returns {string}
138 */
139 static createMultiErrorMessage(err: GoogleErrorBody, errors?: GoogleInnerError[]): string;
140}
141/**
142 * Custom error type for partial errors returned from the API.
143 *
144 * @param {object} b - Error object.
145 */
146export declare class PartialFailureError extends Error {
147 errors?: GoogleInnerError[];
148 response?: r.Response;
149 constructor(b: GoogleErrorBody);
150}
151export interface BodyResponseCallback {
152 (err: Error | ApiError | null, body?: ResponseBody, res?: r.Response): void;
153}
154export interface RetryOptions {
155 retryDelayMultiplier?: number;
156 totalTimeout?: number;
157 maxRetryDelay?: number;
158 autoRetry?: boolean;
159 maxRetries?: number;
160 retryableErrorFn?: (err: ApiError) => boolean;
161}
162export interface MakeRequestConfig {
163 /**
164 * Automatically retry requests if the response is related to rate limits or
165 * certain intermittent server errors. We will exponentially backoff
166 * subsequent requests by default. (default: true)
167 */
168 autoRetry?: boolean;
169 /**
170 * Maximum number of automatic retries attempted before returning the error.
171 * (default: 3)
172 */
173 maxRetries?: number;
174 retries?: number;
175 retryOptions?: RetryOptions;
176 stream?: Duplexify;
177 shouldRetryFn?: (response?: r.Response) => boolean;
178}
179export declare class Util {
180 ApiError: typeof ApiError;
181 PartialFailureError: typeof PartialFailureError;
182 /**
183 * No op.
184 *
185 * @example
186 * function doSomething(callback) {
187 * callback = callback || noop;
188 * }
189 */
190 noop(): void;
191 /**
192 * Uniformly process an API response.
193 *
194 * @param {*} err - Error value.
195 * @param {*} resp - Response value.
196 * @param {*} body - Body value.
197 * @param {function} callback - The callback function.
198 */
199 handleResp(err: Error | null, resp?: r.Response | null, body?: ResponseBody, callback?: BodyResponseCallback): void;
200 /**
201 * Sniff an incoming HTTP response message for errors.
202 *
203 * @param {object} httpRespMessage - An incoming HTTP response message from `request`.
204 * @return {object} parsedHttpRespMessage - The parsed response.
205 * @param {?error} parsedHttpRespMessage.err - An error detected.
206 * @param {object} parsedHttpRespMessage.resp - The original response object.
207 */
208 parseHttpRespMessage(httpRespMessage: r.Response): ParsedHttpRespMessage;
209 /**
210 * Parse the response body from an HTTP request.
211 *
212 * @param {object} body - The response body.
213 * @return {object} parsedHttpRespMessage - The parsed response.
214 * @param {?error} parsedHttpRespMessage.err - An error detected.
215 * @param {object} parsedHttpRespMessage.body - The original body value provided
216 * will try to be JSON.parse'd. If it's successful, the parsed value will
217 * be returned here, otherwise the original value and an error will be returned.
218 */
219 parseHttpRespBody(body: ResponseBody): ParsedHttpResponseBody;
220 /**
221 * Take a Duplexify stream, fetch an authenticated connection header, and
222 * create an outgoing writable stream.
223 *
224 * @param {Duplexify} dup - Duplexify stream.
225 * @param {object} options - Configuration object.
226 * @param {module:common/connection} options.connection - A connection instance used to get a token with and send the request through.
227 * @param {object} options.metadata - Metadata to send at the head of the request.
228 * @param {object} options.request - Request object, in the format of a standard Node.js http.request() object.
229 * @param {string=} options.request.method - Default: "POST".
230 * @param {string=} options.request.qs.uploadType - Default: "multipart".
231 * @param {string=} options.streamContentType - Default: "application/octet-stream".
232 * @param {function} onComplete - Callback, executed after the writable Request stream has completed.
233 */
234 makeWritableStream(dup: Duplexify, options: MakeWritableStreamOptions, onComplete?: Function): void;
235 /**
236 * Returns true if the API request should be retried, given the error that was
237 * given the first time the request was attempted. This is used for rate limit
238 * related errors as well as intermittent server errors.
239 *
240 * @param {error} err - The API error to check if it is appropriate to retry.
241 * @return {boolean} True if the API request should be retried, false otherwise.
242 */
243 shouldRetryRequest(err?: ApiError): boolean;
244 /**
245 * Get a function for making authenticated requests.
246 *
247 * @param {object} config - Configuration object.
248 * @param {boolean=} config.autoRetry - Automatically retry requests if the
249 * response is related to rate limits or certain intermittent server
250 * errors. We will exponentially backoff subsequent requests by default.
251 * (default: true)
252 * @param {object=} config.credentials - Credentials object.
253 * @param {boolean=} config.customEndpoint - If true, just return the provided request options. Default: false.
254 * @param {string=} config.email - Account email address, required for PEM/P12 usage.
255 * @param {number=} config.maxRetries - Maximum number of automatic retries attempted before returning the error. (default: 3)
256 * @param {string=} config.keyFile - Path to a .json, .pem, or .p12 keyfile.
257 * @param {array} config.scopes - Array of scopes required for the API.
258 */
259 makeAuthenticatedRequestFactory(config: MakeAuthenticatedRequestFactoryConfig): MakeAuthenticatedRequest;
260 /**
261 * Make a request through the `retryRequest` module with built-in error
262 * handling and exponential back off.
263 *
264 * @param {object} reqOpts - Request options in the format `request` expects.
265 * @param {object=} config - Configuration object.
266 * @param {boolean=} config.autoRetry - Automatically retry requests if the
267 * response is related to rate limits or certain intermittent server
268 * errors. We will exponentially backoff subsequent requests by default.
269 * (default: true)
270 * @param {number=} config.maxRetries - Maximum number of automatic retries
271 * attempted before returning the error. (default: 3)
272 * @param {object=} config.request - HTTP module for request calls.
273 * @param {function} callback - The callback function.
274 */
275 makeRequest(reqOpts: DecorateRequestOptions, config: MakeRequestConfig, callback: BodyResponseCallback): void | Abortable;
276 /**
277 * Decorate the options about to be made in a request.
278 *
279 * @param {object} reqOpts - The options to be passed to `request`.
280 * @param {string} projectId - The project ID.
281 * @return {object} reqOpts - The decorated reqOpts.
282 */
283 decorateRequest(reqOpts: DecorateRequestOptions, projectId: string): DecorateRequestOptions;
284 isCustomType(unknown: any, module: string): boolean;
285 /**
286 * Create a properly-formatted User-Agent string from a package.json file.
287 *
288 * @param {object} packageJson - A module's package.json file.
289 * @return {string} userAgent - The formatted User-Agent string.
290 */
291 getUserAgentFromPackageJson(packageJson: PackageJson): string;
292 /**
293 * Given two parameters, figure out if this is either:
294 * - Just a callback function
295 * - An options object, and then a callback function
296 * @param optionsOrCallback An options object or callback.
297 * @param cb A potentially undefined callback.
298 */
299 maybeOptionsOrCallback<T = {}, C = (err?: Error) => void>(optionsOrCallback?: T | C, cb?: C): [T, C];
300}
301declare const util: Util;
302export { util };