forked from firebase/firebase-admin-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-request.ts
More file actions
399 lines (361 loc) · 12.8 KB
/
api-request.ts
File metadata and controls
399 lines (361 loc) · 12.8 KB
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
/*!
* Copyright 2017 Google Inc.
*
* 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 {deepCopy} from './deep-copy';
import {FirebaseApp} from '../firebase-app';
import {AppErrorCodes, FirebaseAppError} from './error';
import * as validator from './validator';
import http = require('http');
import https = require('https');
import url = require('url');
import * as stream from 'stream';
import * as zlibmod from 'zlib';
/** Http method type definition. */
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
/** API callback function type definition. */
export type ApiCallbackFunction = (data: object) => void;
/**
* Configuration for constructing a new HTTP request.
*/
export interface HttpRequestConfig {
method: HttpMethod;
/** Target URL of the request. Should be a well-formed URL including protocol, hostname, port and path. */
url: string;
headers?: {[key: string]: string};
data?: string | object | Buffer;
/** Connect and read timeout (in milliseconds) for the outgoing request. */
timeout?: number;
}
/**
* Represents an HTTP response received from a remote server.
*/
export interface HttpResponse {
readonly status: number;
readonly headers: any;
/** Response data as a raw string. */
readonly text: string;
/** Response data as a parsed JSON object. */
readonly data: any;
/**
* Indicates if the response content is JSON-formatted or not. If true, data field can be used
* to retrieve the content as a parsed JSON object.
*/
isJson(): boolean;
}
interface LowLevelResponse {
status: number;
headers: http.IncomingHttpHeaders;
request: http.ClientRequest;
data: string;
config: HttpRequestConfig;
}
interface LowLevelError extends Error {
config: HttpRequestConfig;
code?: string;
request?: http.ClientRequest;
response?: LowLevelResponse;
}
class DefaultHttpResponse implements HttpResponse {
public readonly status: number;
public readonly headers: any;
public readonly text: string;
private readonly parsedData: any;
private readonly parseError: Error;
private readonly request: string;
/**
* Constructs a new HttpResponse from the given LowLevelResponse.
*/
constructor(resp: LowLevelResponse) {
this.status = resp.status;
this.headers = resp.headers;
this.text = resp.data;
try {
this.parsedData = JSON.parse(resp.data);
} catch (err) {
this.parsedData = undefined;
this.parseError = err;
}
this.request = `${resp.config.method} ${resp.config.url}`;
}
get data(): any {
if (this.isJson()) {
return this.parsedData;
}
throw new FirebaseAppError(
AppErrorCodes.UNABLE_TO_PARSE_RESPONSE,
`Error while parsing response data: "${ this.parseError.toString() }". Raw server ` +
`response: "${ this.text }". Status code: "${ this.status }". Outgoing ` +
`request: "${ this.request }."`,
);
}
public isJson(): boolean {
return typeof this.parsedData !== 'undefined';
}
}
export class HttpError extends Error {
constructor(public readonly response: HttpResponse) {
super(`Server responded with status ${response.status}.`);
// Set the prototype so that instanceof checks will work correctly.
// See: https://github.com/Microsoft/TypeScript/issues/13965
Object.setPrototypeOf(this, HttpError.prototype);
}
}
export class HttpClient {
/**
* Sends an HTTP request to a remote server. If the server responds with a successful response (2xx), the returned
* promise resolves with an HttpResponse. If the server responds with an error (3xx, 4xx, 5xx), the promise rejects
* with an HttpError. In case of all other errors, the promise rejects with a FirebaseAppError. If a request fails
* due to a low-level network error, transparently retries the request once before rejecting the promise.
*
* If the request data is specified as an object, it will be serialized into a JSON string. The application/json
* content-type header will also be automatically set in this case. For all other payload types, the content-type
* header should be explicitly set by the caller. To send a JSON leaf value (e.g. "foo", 5), parse it into JSON,
* and pass as a string or a Buffer along with the appropriate content-type header.
*
* @param {HttpRequest} request HTTP request to be sent.
* @return {Promise<HttpResponse>} A promise that resolves with the response details.
*/
public send(config: HttpRequestConfig): Promise<HttpResponse> {
return this.sendWithRetry(config);
}
/**
* Sends an HTTP request, and retries it once in case of low-level network errors.
*/
private sendWithRetry(config: HttpRequestConfig, attempts: number = 0): Promise<HttpResponse> {
return sendRequest(config)
.then((resp) => {
return new DefaultHttpResponse(resp);
}).catch((err: LowLevelError) => {
const retryCodes = ['ECONNRESET', 'ETIMEDOUT'];
if (retryCodes.indexOf(err.code) !== -1 && attempts === 0) {
return this.sendWithRetry(config, attempts + 1);
}
if (err.response) {
throw new HttpError(new DefaultHttpResponse(err.response));
}
if (err.code === 'ETIMEDOUT') {
throw new FirebaseAppError(
AppErrorCodes.NETWORK_TIMEOUT,
`Error while making request: ${err.message}.`);
}
throw new FirebaseAppError(
AppErrorCodes.NETWORK_ERROR,
`Error while making request: ${err.message}. Error code: ${err.code}`);
});
}
}
/**
* Sends an HTTP request based on the provided configuration. This is a wrapper around the http and https
* packages of Node.js, providing content processing, timeouts and error handling.
*/
function sendRequest(config: HttpRequestConfig): Promise<LowLevelResponse> {
return new Promise((resolve, reject) => {
let data: Buffer;
const headers = config.headers || {};
if (config.data) {
if (validator.isObject(config.data)) {
data = new Buffer(JSON.stringify(config.data), 'utf-8');
if (typeof headers['Content-Type'] === 'undefined') {
headers['Content-Type'] = 'application/json;charset=utf-8';
}
} else if (validator.isString(config.data)) {
data = new Buffer(config.data as string, 'utf-8');
} else if (validator.isBuffer(config.data)) {
data = config.data as Buffer;
} else {
return reject(createError(
'Request data must be a string, a Buffer or a json serializable object',
config,
));
}
// Add Content-Length header if data exists
headers['Content-Length'] = data.length.toString();
}
const parsed = url.parse(config.url);
const protocol = parsed.protocol || 'https:';
const isHttps = protocol === 'https:';
const options = {
hostname: parsed.hostname,
port: parsed.port,
path: parsed.path,
method: config.method,
headers,
};
const transport: any = isHttps ? https : http;
const req: http.ClientRequest = transport.request(options, (res: http.IncomingMessage) => {
if (req.aborted) {
return;
}
// Uncompress the response body transparently if required.
let respStream: stream.Readable = res;
const encodings = ['gzip', 'compress', 'deflate'];
if (encodings.indexOf(res.headers['content-encoding']) !== -1) {
// Add the unzipper to the body stream processing pipeline.
const zlib: typeof zlibmod = require('zlib');
respStream = respStream.pipe(zlib.createUnzip());
// Remove the content-encoding in order to not confuse downstream operations.
delete res.headers['content-encoding'];
}
const response: LowLevelResponse = {
status: res.statusCode,
headers: res.headers,
request: req,
data: undefined,
config,
};
const responseBuffer = [];
respStream.on('data', (chunk) => {
responseBuffer.push(chunk);
});
respStream.on('error', (err) => {
if (req.aborted) {
return;
}
reject(enhanceError(err, config, null, req));
});
respStream.on('end', () => {
const responseData = Buffer.concat(responseBuffer).toString();
response.data = responseData;
finalizeRequest(resolve, reject, response);
});
});
// Handle errors
req.on('error', (err) => {
if (req.aborted) {
return;
}
reject(enhanceError(err, config, null, req));
});
if (config.timeout) {
// Listen to timeouts and throw an error.
req.setTimeout(config.timeout, () => {
req.abort();
reject(createError(`timeout of ${config.timeout}ms exceeded`, config, 'ETIMEDOUT', req));
});
}
// Send the request
req.end(data);
});
}
/**
* Creates a new error from the given message, and enhances it with other information available.
*/
function createError(
message: string,
config: HttpRequestConfig,
code?: string,
request?: http.ClientRequest,
response?: LowLevelResponse): LowLevelError {
const error = new Error(message);
return enhanceError(error, config, code, request, response);
}
/**
* Enhances the given error by adding more information to it. Specifically, the HttpRequestConfig,
* the underlying request and response will be attached to the error.
*/
function enhanceError(
error,
config: HttpRequestConfig,
code: string,
request: http.ClientRequest,
response?: LowLevelResponse): LowLevelError {
error.config = config;
if (code) {
error.code = code;
}
error.request = request;
error.response = response;
return error;
}
/**
* Finalizes the current request in-flight by either resolving or rejecting the associated promise. In the event
* of an error, adds additional useful information to the returned error.
*/
function finalizeRequest(resolve, reject, response: LowLevelResponse) {
if (response.status >= 200 && response.status < 300) {
resolve(response);
} else {
reject(createError(
'Request failed with status code ' + response.status,
response.config,
null,
response.request,
response,
));
}
}
export class AuthorizedHttpClient extends HttpClient {
constructor(private readonly app: FirebaseApp) {
super();
}
public send(request: HttpRequestConfig): Promise<HttpResponse> {
return this.app.INTERNAL.getToken().then((accessTokenObj) => {
const requestCopy = deepCopy(request);
requestCopy.headers = requestCopy.headers || {};
const authHeader = 'Authorization';
requestCopy.headers[authHeader] = `Bearer ${accessTokenObj.accessToken}`;
return super.send(requestCopy);
});
}
}
/**
* Class that defines all the settings for the backend API endpoint.
*
* @param {string} endpoint The Firebase Auth backend endpoint.
* @param {HttpMethod} httpMethod The http method for that endpoint.
* @constructor
*/
export class ApiSettings {
private requestValidator: ApiCallbackFunction;
private responseValidator: ApiCallbackFunction;
constructor(private endpoint: string, private httpMethod: HttpMethod = 'POST') {
this.setRequestValidator(null)
.setResponseValidator(null);
}
/** @return {string} The backend API endpoint. */
public getEndpoint(): string {
return this.endpoint;
}
/** @return {HttpMethod} The request HTTP method. */
public getHttpMethod(): HttpMethod {
return this.httpMethod;
}
/**
* @param {ApiCallbackFunction} requestValidator The request validator.
* @return {ApiSettings} The current API settings instance.
*/
public setRequestValidator(requestValidator: ApiCallbackFunction): ApiSettings {
const nullFunction = (request: object) => undefined;
this.requestValidator = requestValidator || nullFunction;
return this;
}
/** @return {ApiCallbackFunction} The request validator. */
public getRequestValidator(): ApiCallbackFunction {
return this.requestValidator;
}
/**
* @param {ApiCallbackFunction} responseValidator The response validator.
* @return {ApiSettings} The current API settings instance.
*/
public setResponseValidator(responseValidator: ApiCallbackFunction): ApiSettings {
const nullFunction = (request: object) => undefined;
this.responseValidator = responseValidator || nullFunction;
return this;
}
/** @return {ApiCallbackFunction} The response validator. */
public getResponseValidator(): ApiCallbackFunction {
return this.responseValidator;
}
}