Repository navigation
Expand file tree
/
Copy pathHttpRequest.ts
More file actions
482 lines (420 loc) · 15.1 KB
/
Copy pathHttpRequest.ts
File metadata and controls
482 lines (420 loc) · 15.1 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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
import {NebulaService, ProxyServer} from "./NebulaService";
import {JsonObject, nbLogger} from "./Head";
import {http2} from "./NodeSupport";
import * as _tls from "tls";
import {Promise} from "es6-promise";
import {Buffer} from "buffer";
import {HttpNode} from "./HttpNode";
import {HttpXhr} from "./HttpXhr";
/**
* APIリクエストインタフェース。
* HttpRequest, _SdeRequest が implement する
* @private
*/
export interface ApiRequest {
execute(): Promise<any>;
setData(data: any): void;
setMethod?(method: string): void;
setContentType?(type: string): void;
setQueryParam?(key: string, value: any): void;
setQueryParams?(params: any): void;
setSessionToken?(token: string): void;
}
export interface Headers {
[index: string]: string;
}
export interface QueryParams {
[index: string]: string;
}
/**
* XHRが定義されているか調べる
* @returns {boolean}
* @private
*/
export const _hasXhr = (): boolean => {
return typeof XMLHttpRequest !== "undefined";
}
export abstract class HttpRequestExecutor {
_req: HttpRequest;
_resolve: any;
_reject: any;
static _xhrFactory: (req: HttpRequest) => HttpRequestExecutor;
static _nodeFactory: (req: HttpRequest) => HttpRequestExecutor;
constructor(req: HttpRequest) {
this._req = req;
this._resolve = req._resolve;
this._reject = req._reject;
}
/**
* リクエスト実行
* @param {string} method
* @param {string} url
* @param {Headers} headers
* @param {any} body
* @param {number} timeout
* @param {string} responseType
* @param {boolean} receiveResponseHeaders
* @param {boolean} useHttp2
*/
abstract execute(method: string, url: string, headers: Headers, body: any, timeout: number,
responseType: string, receiveResponseHeaders: boolean, useHttp2: boolean): void;
abstract setReturnRawMessage(rawMessage: boolean): void;
/**
* セッションをcloseする (Node.js 使用時、HTTP/2使用時のみ有効)
* @param {string} authority 対象のauthority (例: 'http://example.com:1234' パスやパラメータは含めない)
* <p>未指定の場合は、保持する全てのHTTP/2セッションをcloseする。
*/
static closeHttp2Session(authority?: string): void {
if (_hasXhr()) {
HttpXhr.closeHttp2Session(authority);
} else {
// close session
HttpNode.closeHttp2Session(authority);
}
}
/**
* HttpRequestExecutor のファクトリメソッド
* @param {HttpRequest} req
* @return {HttpRequestExecutor}
*/
static create(req: HttpRequest): HttpRequestExecutor {
if (_hasXhr()) {
return this._xhrFactory(req);
} else {
return this._nodeFactory(req);
}
}
static setXhrFactory(factory: (req: HttpRequest) => HttpRequestExecutor) {
this._xhrFactory = factory;
}
static setNodeFactory(factory: (req: HttpRequest) => HttpRequestExecutor) {
this._nodeFactory = factory;
}
}
/*
* HTTPリクエスト クラス
*/
export class HttpRequest implements ApiRequest {
private _service: any;
private _method: string;
private _url: string;
private _headers: Headers;
private _contentType: string;
private _responseType: string;
private _queryParams: QueryParams;
private _data: any;
private _sessionToken: string;
private _timeout: number;
private _rawMessage: boolean = false;
private _useHttp2: boolean = false;
_resolve: any;
_reject: any;
private _receiveResponseHeaders: boolean;
private _responseHeaders: object;
private static _defaultTimeout = 0;
static _httpAgent: any;
static _httpsAgent: any;
static _httpsAgentOptions: _tls.SecureContextOptions;
static _proxy: ProxyServer;
static getProxy(): ProxyServer {
return HttpRequest._proxy;
}
static setProxy(proxy: ProxyServer) {
HttpRequest._proxy = proxy;
}
static setHttpAgent(agent: any) {
HttpRequest._httpAgent = agent;
}
static setHttpsAgent(agent: any, options?: any) {
HttpRequest._httpsAgent = agent;
HttpRequest._httpsAgentOptions = options;
}
// internal use only
get service(): any {
return this._service;
}
/**
* @description レスポンスヘッダ(Node.js のみ)
* @name HttpRequest#responseHeaders
* @type {Object}
*/
get responseHeaders(): object {
return this._responseHeaders;
}
set responseHeaders(value: object) {
this._responseHeaders = value;
}
/**
* @memberOf HttpRequest
* @description デフォルト通信タイムアウト値を設定する
* @param {number} timeout タイムアウト値(ミリ秒)
*/
static setDefaultTimeout(timeout: number) {
this._defaultTimeout = timeout;
}
/**
* @memberOf HttpRequest
* @description デフォルト通信タイムアウト値を取得する
* @return {number} タイムアウト値(ミリ秒)
*/
static getDefaultTimeout(): number {
return this._defaultTimeout;
}
/**
* @description raw response message を返す場合に true をセットする (Node.js専用)。
* <p>true を指定すると、execute 成功時の応答は http.IncomingMessage となる。
* <p>HTTP/2を使用する場合、http2.ClientHttp2Streamとなる。
* @name HttpRequest#rawMessage
* @type {boolean}
*/
get rawMessage(): boolean {
return this._rawMessage;
}
set rawMessage(value: boolean) {
this._rawMessage = value;
}
/**
* @memberOf HttpRequest
* @description HTTP/2 を使用する場合にtrueをセットする。(Node.js専用)。
* @name HttpRequest#useHttp2
* @type {boolean}
*/
get useHttp2(): boolean {
return this._useHttp2;
}
set useHttp2(value: boolean) {
if (value && http2 == null) {
throw new Error("No http2 support.");
}
this._useHttp2 = value;
}
/**
* @class HttpRequest
* @classdesc HTTPリクエストクラス
* @description コンストラクタ。
* <p>
* ユーザがログイン中の場合、自動的に SessionToken が設定される。
* @param {NebulaService} service NebulaService
* @param {string} path パス
* @param {Object} option オプション。noprefix プロパティに true を設定すると、パスプレフィクス("/1/{tenantId}")を付与しない。
*/
constructor(service: NebulaService, path: string, option?: JsonObject) {
nbLogger("HttpRequest#start:path = " + path);
this._service = service;
this._url = this._service.getBaseUri();
if (!(option && option.noprefix)) {
this._url += "/" + this._service.getRestApiVersion() + "/" + this._service.getTenantID();
}
// path に含まれるグループ名やファイル名(日本語の場合あり)は、 encodeURIComponent で事前に encode されている。
// クエリパラメータ(?, &, =) などは素通し
this._url = encodeURI(this._url) + path;
this._headers = {};
this._contentType = null;
this._responseType = null;
this._queryParams = null;
this._data = null;
this._receiveResponseHeaders = false;
this._timeout = HttpRequest.getDefaultTimeout();
this._useHttp2 = this._service.getHttp2();
const _currentObj = this._service.getCurrentUser();
if (_currentObj === null) {
this._sessionToken = null;
} else {
this._sessionToken = _currentObj.sessionToken;
}
}
/**
* @memberOf HttpRequest
* @description レスポンスヘッダ受信設定を行う。
* <p>
* true に設定すると、execute 成功時の応答は
* {body: ..., headers: {...}, status: statusCode}
* 形式となる。
* <p>
* ブラウザ(XHR)の場合は、headers は文字列(全ヘッダ連結したもの)、
* Node.js の場合は headers はヘッダ名をキーとした Object となる。
* @param {boolean} receive true の場合はレスポンスヘッダを受信する
* @return {HttpRequest} this
*/
setReceiveResponseHeaders(receive: boolean): HttpRequest {
this._receiveResponseHeaders = receive;
return this;
}
/**
* @memberOf HttpRequest
* @description HTTP リクエストを実行する。
* X-Application-Id, X-Application-Key, X-Session-Token ヘッダは自動的に付与される。
* @return {Promise} Promise
*/
execute(): Promise<any> {
return new Promise((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
this._headers["X-Application-Id"] = this._service.getAppID();
this._headers["X-Application-Key"] = this._service.getAppKey();
// ヘッダ
if (this._contentType !== null) {
this._headers["Content-Type"] = this._contentType;
}
if (this._sessionToken !== null) {
this._headers["X-Session-Token"] = this._sessionToken;
}
let url = this._url;
// クエリパラメータ
if (this._queryParams) {
const p: string[] = [];
for (const key of Object.keys(this._queryParams)) {
if (this._queryParams.hasOwnProperty(key)) {
p.push(encodeURIComponent(key) + "=" + encodeURIComponent(this._queryParams[key]));
}
}
if (p.length > 0) {
url += "?" + p.join("&");
}
}
// ボディ
let body: any;
if (!(this._data != null)) {
body = null;
} else if (
(typeof this._data === "string") ||
(typeof Blob !== "undefined" && Blob !== null && this._data instanceof Blob) ||
(typeof Buffer !== "undefined" && Buffer !== null && Buffer.isBuffer(this._data))) {
body = this._data;
} else {
body = JSON.stringify(this._data);
}
const executor = HttpRequestExecutor.create(this);
if (this._rawMessage) {
executor.setReturnRawMessage(this._rawMessage);
}
executor.execute(this._method, url, this._headers, body, this._timeout,
this._responseType, this._receiveResponseHeaders, this._useHttp2);
});
}
/**
* @memberOf HttpRequest
* @dscription セッションをcloseする (Node.js 使用時、HTTP/2使用時のみ有効)
* @param {string} authority 対象のauthority 未指定の場合は全てのセッションをcloseする
*/
static closeHttp2Session(authority?: string): void {
HttpRequestExecutor.closeHttp2Session(authority);
}
/**
* @memberOf HttpRequest
* @description HTTP メソッドを設定する
* @param {string} method メソッド
* @return {HttpRequest} this
*/
setMethod(method: string): HttpRequest {
this._method = method;
return this;
}
/**
* @memberOf HttpRequest
* @description Content-Type 設定する
* @param {string} contentType Content-Type
* @return {HttpRequest} this
*/
setContentType(contentType: string): HttpRequest {
this._contentType = contentType;
return this;
}
/**
* @memberOf HttpRequest
* @description クエリパラメータを設定する。以前設定されていた値は消去される。
* @param {Object} params パラメータ(Object形式)
* @return {HttpRequest} this
*/
setQueryParams(params: QueryParams): HttpRequest {
this._queryParams = params;
return this;
}
/**
* @memberOf HttpRequest
* @description クエリパラメータを追加する。以前設定されていた値に追加される。
* @param {Object} params パラメータ(Object形式)
* @return {HttpRequest} this
*/
addQueryParams(params: QueryParams): HttpRequest {
if (params) {
for (const key of Object.keys(params)) {
this.setQueryParam(key, params[key]);
}
}
return this;
}
/**
* @memberOf HttpRequest
* @description クエリパラメータ(1件)を設定する
* @param {string} key パラメータ名
* @param {Object} value 値
* @return {HttpRequest} this
*/
setQueryParam(key: string, value: any): HttpRequest {
if (!this._queryParams) {
this._queryParams = {};
}
this._queryParams[key] = value;
return this;
}
/**
* @memberOf HttpRequest
* @description 送信データを設定する。
* <p>
* 文字列を指定した場合は文字列がそのまま設定される。
* Objectを指定した場合は JSON 文字列に変換される。
* Blob および Buffer を指定した場合は、バイナリデータが設定される。
* @param {Object} data データ
* @return {HttpRequest} this
*/
setData(data: any): HttpRequest {
this._data = data;
return this;
}
/**
* @memberOf HttpRequest
* @description SessionToken を設定する。
* <p>
* 通常は本クラスのインスタンス生成時点で自動的に SessionToken は設定されている(ユーザログイン済みの場合)
* @param {string} sessionToken セッショントークン文字列
* @return {HttpRequest} this
*/
setSessionToken(sessionToken: string): HttpRequest {
this._sessionToken = sessionToken;
return this;
}
/**
* @memberOf HttpRequest
* @description ResponseType を設定する。
* 指定できるタイプは以下のいずれかで、返却されるレスポンスの型が変化する。
* デフォルトは "text"。
* <ul>
* <li>text : 文字列</li>
* <li>json : JSON。レスポンスは JSON.parse されたもの。</li>
* <li>blob : blob (ブラウザのみ)</li>
* <li>buffer : Buffer (Node.jsのみ)</li>
* </ul>
* @param {string} responseType レスポンスタイプ
* @return {HttpRequest} this
*/
setResponseType(responseType: string): HttpRequest {
this._responseType = responseType;
return this;
}
/**
* @memberOf HttpRequest
* @description リクエストヘッダを設定する。
* <p>注: 1つのヘッダに対して設定できる値は1つのみである。
* @param {string} header ヘッダ名
* @param {string} value 値
* @return {HttpRequest} this
*/
addRequestHeader(header: string, value: string): HttpRequest {
if (this._headers[header] !== undefined) {
nbLogger("HTTP Request Warning : This header already exists.");
}
this._headers[header] = value;
return this;
}
}