@motionpicture/coa-service 9.2.0 → 9.3.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +1 -6
  2. package/example/findFilms.js +19 -2
  3. package/example/findKubunNames.js +6 -3
  4. package/example/findPerformances.js +1 -1
  5. package/example/findScreen.js +1 -1
  6. package/example/findTheater.js +1 -1
  7. package/example/findTickets.js +1 -1
  8. package/example/getToken.js +21 -0
  9. package/example/salesTicket.js +6 -5
  10. package/example/stateReserve.js +1 -1
  11. package/example/stateReserveSeat.js +1 -1
  12. package/lib/auth/credentials.d.ts +1 -2
  13. package/lib/auth/refreshTokenClient.d.ts +11 -6
  14. package/lib/auth/refreshTokenClient.js +81 -4
  15. package/lib/index.d.ts +1 -1
  16. package/lib/index.js +1 -1
  17. package/lib/service.d.ts +4 -3
  18. package/lib/transporters.d.ts +35 -6
  19. package/lib/transporters.js +114 -4
  20. package/package.json +7 -10
  21. package/docs/assets/css/main.css +0 -1
  22. package/docs/assets/images/icons.png +0 -0
  23. package/docs/assets/images/icons@2x.png +0 -0
  24. package/docs/assets/images/widgets.png +0 -0
  25. package/docs/assets/images/widgets@2x.png +0 -0
  26. package/docs/assets/js/main.js +0 -51
  27. package/docs/assets/js/search.json +0 -1
  28. package/docs/classes/_auth_refreshtokenclient_.refreshtokenclient.html +0 -517
  29. package/docs/classes/_index_.auth.refreshtoken.html +0 -529
  30. package/docs/classes/_index_.service.master.html +0 -599
  31. package/docs/classes/_index_.service.reserve.html +0 -594
  32. package/docs/classes/_service_.service.html +0 -316
  33. package/docs/classes/_service_master_.masterservice.html +0 -583
  34. package/docs/classes/_service_reserve_.reserveservice.html +0 -578
  35. package/docs/classes/_transporters_.coaserviceerror.html +0 -370
  36. package/docs/classes/_transporters_.defaulttransporter.html +0 -408
  37. package/docs/classes/_transporters_.transporter.html +0 -246
  38. package/docs/enums/_factory_master_.flgearlybooking.html +0 -277
  39. package/docs/enums/_factory_master_.flgmember.html +0 -277
  40. package/docs/enums/_factory_reserve_.flgmember.html +0 -295
  41. package/docs/globals.html +0 -173
  42. package/docs/index.html +0 -249
  43. package/docs/interfaces/_auth_credentials_.icredentials.html +0 -232
  44. package/docs/interfaces/_auth_refreshtokenclient_.ioptions.html +0 -221
  45. package/docs/interfaces/_factory_master_.ikubunnameargs.html +0 -286
  46. package/docs/interfaces/_factory_master_.ikubunnameresult.html +0 -324
  47. package/docs/interfaces/_factory_master_.imgtkticketcodeargs.html +0 -343
  48. package/docs/interfaces/_factory_master_.imgtkticketcoderesult.html +0 -362
  49. package/docs/interfaces/_factory_master_.imvtkticketcodeargs.html +0 -438
  50. package/docs/interfaces/_factory_master_.imvtkticketcoderesult.html +0 -362
  51. package/docs/interfaces/_factory_master_.ischeduleargs.html +0 -305
  52. package/docs/interfaces/_factory_master_.ischeduleresult.html +0 -518
  53. package/docs/interfaces/_factory_master_.iscreenargs.html +0 -267
  54. package/docs/interfaces/_factory_master_.iscreenresult.html +0 -324
  55. package/docs/interfaces/_factory_master_.iscreenseat.html +0 -381
  56. package/docs/interfaces/_factory_master_.itheaterargs.html +0 -267
  57. package/docs/interfaces/_factory_master_.itheaterresult.html +0 -343
  58. package/docs/interfaces/_factory_master_.iticketargs.html +0 -267
  59. package/docs/interfaces/_factory_master_.iticketresult.html +0 -362
  60. package/docs/interfaces/_factory_master_.ititleargs.html +0 -267
  61. package/docs/interfaces/_factory_master_.ititleresult.html +0 -552
  62. package/docs/interfaces/_factory_reserve_.icountfreeseatargs.html +0 -323
  63. package/docs/interfaces/_factory_reserve_.icountfreeseatdate.html +0 -323
  64. package/docs/interfaces/_factory_reserve_.icountfreeseatperformance.html +0 -380
  65. package/docs/interfaces/_factory_reserve_.icountfreeseatresult.html +0 -304
  66. package/docs/interfaces/_factory_reserve_.idelreserveargs.html +0 -418
  67. package/docs/interfaces/_factory_reserve_.idelreserveseat.html +0 -304
  68. package/docs/interfaces/_factory_reserve_.ideltmpreserveargs.html +0 -380
  69. package/docs/interfaces/_factory_reserve_.isalesticketargs.html +0 -380
  70. package/docs/interfaces/_factory_reserve_.isalesticketresult.html +0 -475
  71. package/docs/interfaces/_factory_reserve_.istatereserveargs.html +0 -323
  72. package/docs/interfaces/_factory_reserve_.istatereserveresult.html +0 -380
  73. package/docs/interfaces/_factory_reserve_.istatereserveseatargs.html +0 -380
  74. package/docs/interfaces/_factory_reserve_.istatereserveseatfreeseat.html +0 -345
  75. package/docs/interfaces/_factory_reserve_.istatereserveseatresult.html +0 -323
  76. package/docs/interfaces/_factory_reserve_.istatereserveseatseat.html +0 -304
  77. package/docs/interfaces/_factory_reserve_.istatereserveticket.html +0 -411
  78. package/docs/interfaces/_factory_reserve_.iupdreserveargs.html +0 -494
  79. package/docs/interfaces/_factory_reserve_.iupdreserveqr.html +0 -323
  80. package/docs/interfaces/_factory_reserve_.iupdreserveresult.html +0 -304
  81. package/docs/interfaces/_factory_reserve_.iupdreserveticket.html +0 -647
  82. package/docs/interfaces/_factory_reserve_.iupdtmpreserveseatargs.html +0 -399
  83. package/docs/interfaces/_factory_reserve_.iupdtmpreserveseatresult.html +0 -304
  84. package/docs/interfaces/_factory_reserve_.iupdtmpreserveseatseat.html +0 -304
  85. package/docs/interfaces/_factory_reserve_.iupdtmpreserveseattmpreserve.html +0 -323
  86. package/docs/interfaces/_service_.ioptions.html +0 -225
  87. package/docs/modules/_auth_credentials_.html +0 -167
  88. package/docs/modules/_auth_refreshtokenclient_.html +0 -198
  89. package/docs/modules/_auth_refreshtokenclient_spec_.html +0 -208
  90. package/docs/modules/_factory_.html +0 -194
  91. package/docs/modules/_factory_master_.html +0 -244
  92. package/docs/modules/_factory_reserve_.html +0 -268
  93. package/docs/modules/_index_.auth.html +0 -178
  94. package/docs/modules/_index_.html +0 -195
  95. package/docs/modules/_index_.service.html +0 -189
  96. package/docs/modules/_service_.html +0 -176
  97. package/docs/modules/_service_master_.html +0 -167
  98. package/docs/modules/_service_master_spec_.html +0 -208
  99. package/docs/modules/_service_reserve_.html +0 -167
  100. package/docs/modules/_service_reserve_spec_.html +0 -208
  101. package/docs/modules/_transporters_.html +0 -253
package/README.md CHANGED
@@ -6,7 +6,7 @@
6
6
  [![Known Vulnerabilities](https://snyk.io/test/github/motionpicture/coa-service/badge.svg)](https://snyk.io/test/github/motionpicture/coa-service)
7
7
  [![npm](https://img.shields.io/npm/dm/@motionpicture/coa-service.svg)](https://nodei.co/npm/@motionpicture/coa-service/)
8
8
 
9
- Node.jsでCOAサービスを使うためのライブラリです。
9
+ COA SDK for Node.js
10
10
 
11
11
  ## Table of contents
12
12
 
@@ -18,7 +18,6 @@ Node.jsでCOAサービスを使うためのライブラリです。
18
18
  - [劇場情報を取得する](#劇場情報を取得する)
19
19
  - [Code Samples](#code-samples)
20
20
  - [Documentation](#documentation)
21
- - [License](#license)
22
21
 
23
22
  ## Specification
24
23
 
@@ -78,7 +77,3 @@ Code sample are [here](https://github.com/motionpicture/coa-service/tree/master/
78
77
  ## Documentation
79
78
 
80
79
  `npm run doc` emits typedoc to ./docs.
81
-
82
- ## License
83
-
84
- ISC
@@ -3,6 +3,7 @@
3
3
  */
4
4
  const COA = require('../');
5
5
  const fs = require('fs');
6
+ const moment = require('moment');
6
7
 
7
8
  const service = new COA.service.Master(
8
9
  {
@@ -11,14 +12,30 @@ const service = new COA.service.Master(
11
12
  endpoint: process.env.COA_ENDPOINT,
12
13
  refreshToken: process.env.COA_REFRESH_TOKEN
13
14
  })
14
- }
15
+ },
16
+ { timeout: 1000 }
15
17
  );
16
18
 
17
19
  service.title({
18
- theaterCode: '118'
20
+ theaterCode: '120'
19
21
  }).then((result) => {
20
22
  fs.writeFileSync(`${__dirname}/output/title.json`, JSON.stringify(result, null, ' '));
21
23
  console.log(result);
24
+ const someMonthsAgo = moment()
25
+ // tslint:disable-next-line:no-magic-numbers
26
+ .add(-3, 'months');
27
+ const filteredResult = result.filter((filmFromCOA) => {
28
+ const startDate = (moment(`${filmFromCOA.dateBegin} +09:00`, 'YYYYMMDD Z')
29
+ .isValid())
30
+ ? moment(`${filmFromCOA.dateBegin} +09:00`, 'YYYYMMDD Z')
31
+ .toDate()
32
+ : moment('2018-01-01T00:00:00+09:00') // 値がない場合、十分に長く
33
+ .toDate();
34
+
35
+ return moment(startDate)
36
+ .isAfter(someMonthsAgo);
37
+ });
38
+ console.log(filteredResult.length);
22
39
  }).catch((err) => {
23
40
  console.error(err);
24
41
  });
@@ -14,11 +14,14 @@ const service = new COA.service.Master(
14
14
  }
15
15
  );
16
16
 
17
+ // const kubunClass = '000'; // すべて
18
+ // const kubunClass = '050'; // 特別席区分
19
+ const kubunClass = '005'; // 販売区分
17
20
  service.kubunName({
18
- theaterCode: '118',
19
- kubunClass: '000'
21
+ theaterCode: '120',
22
+ kubunClass
20
23
  }).then((result) => {
21
- fs.writeFileSync(`${__dirname}/output/kubunName.json`, JSON.stringify(result, null, ' '));
24
+ fs.writeFileSync(`${__dirname}/output/kubunName-${kubunClass}.json`, JSON.stringify(result, null, ' '));
22
25
  console.log(result);
23
26
  }).catch((err) => {
24
27
  console.error(err);
@@ -16,7 +16,7 @@ const service = new COA.service.Master(
16
16
  );
17
17
 
18
18
  service.schedule({
19
- theaterCode: '012',
19
+ theaterCode: '120',
20
20
  begin: '20200213',
21
21
  end: '20200218'
22
22
  }).then((result) => {
@@ -15,7 +15,7 @@ const service = new COA.service.Master(
15
15
  );
16
16
 
17
17
  service.screen({
18
- theaterCode: '118'
18
+ theaterCode: '120'
19
19
  }).then((result) => {
20
20
  fs.writeFileSync(`${__dirname}/output/screen.json`, JSON.stringify(result, null, ' '));
21
21
  console.log(result);
@@ -15,7 +15,7 @@ const service = new COA.service.Master(
15
15
  );
16
16
 
17
17
  service.theater({
18
- theaterCode: '118'
18
+ theaterCode: '120'
19
19
  }).then((result) => {
20
20
  fs.writeFileSync(`${__dirname}/output/theater.json`, JSON.stringify(result, null, ' '));
21
21
  console.log(result);
@@ -15,7 +15,7 @@ const service = new COA.service.Master(
15
15
  );
16
16
 
17
17
  service.ticket({
18
- theaterCode: '118'
18
+ theaterCode: '120'
19
19
  }).then((result) => {
20
20
  fs.writeFileSync(`${__dirname}/output/ticket.json`, JSON.stringify(result, null, ' '));
21
21
  console.log(result);
@@ -0,0 +1,21 @@
1
+ const COA = require('../');
2
+
3
+ const auth = new COA.auth.RefreshToken({
4
+ endpoint: process.env.COA_ENDPOINT,
5
+ refreshToken: process.env.COA_REFRESH_TOKEN
6
+ });
7
+
8
+ auth.getToken()
9
+ .then((result) => {
10
+ console.log('getToken result:', result);
11
+ }).catch((err) => {
12
+ console.error(err);
13
+ });
14
+
15
+
16
+ auth.getTokenWithFetch()
17
+ .then((result) => {
18
+ console.log('getTokenWithFetch result:', result);
19
+ }).catch((err) => {
20
+ console.error(err);
21
+ });
@@ -15,13 +15,14 @@ const service = new COA.service.Reserve(
15
15
  );
16
16
 
17
17
  service.salesTicket({
18
- theaterCode: '118',
19
- dateJouei: '20170411',
20
- titleCode: '99600',
18
+ theaterCode: '120',
19
+ dateJouei: '20230309',
20
+ titleCode: '99100',
21
21
  titleBranchNum: '0',
22
- timeBegin: '2130'
22
+ timeBegin: '1720',
23
+ flgMember: '1'
23
24
  }).then((result) => {
24
- fs.writeFileSync(`${__dirname}/output/salesTicket.json`, JSON.stringify(result, null, ' '));
25
+ fs.writeFileSync(`${__dirname}/output/salesTicket2.json`, JSON.stringify(result, null, ' '));
25
26
  console.log(result);
26
27
  }).catch((err) => {
27
28
  console.error(err);
@@ -13,7 +13,7 @@ const service = new COA.service.Reserve({
13
13
  });
14
14
 
15
15
  service.stateReserve({
16
- theaterCode: '118',
16
+ theaterCode: '120',
17
17
  reserveNum: '99150',
18
18
  telNum: '09012345678'
19
19
  }).then((result) => {
@@ -15,7 +15,7 @@ const service = new COA.service.Reserve(
15
15
  );
16
16
 
17
17
  service.stateReserveSeat({
18
- theaterCode: '118',
18
+ theaterCode: '120',
19
19
  dateJouei: '20190605',
20
20
  titleCode: '16421',
21
21
  titleBranchNum: '0',
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * 認証情報インターフェース
3
3
  */
4
- interface ICredentials {
4
+ export interface ICredentials {
5
5
  /**
6
6
  * アクセストークン
7
7
  */
@@ -11,4 +11,3 @@ interface ICredentials {
11
11
  */
12
12
  expired_at?: string;
13
13
  }
14
- export default ICredentials;
@@ -1,13 +1,14 @@
1
- import * as request from 'request';
2
- import ICredentials from './credentials';
1
+ import { IRequestOptions } from '../transporters';
2
+ import { ICredentials } from './credentials';
3
3
  export interface IOptions {
4
4
  endpoint: string;
5
5
  refreshToken?: string;
6
6
  }
7
+ export { IRequestOptions };
7
8
  /**
8
9
  * リフレッシュトークン認証クライアント
9
10
  */
10
- export default class RefreshTokenClient {
11
+ export declare class RefreshTokenClient {
11
12
  /**
12
13
  * アクセストークンの有効期限までの猶予時間初期値
13
14
  */
@@ -18,7 +19,11 @@ export default class RefreshTokenClient {
18
19
  /**
19
20
  * トークンエンドポイントからアクセストークンを取得します。
20
21
  */
21
- getToken(): Promise<ICredentials>;
22
+ getTokenWithRequest(): Promise<ICredentials>;
23
+ /**
24
+ * トークンエンドポイントからアクセストークンを取得します。
25
+ */
26
+ getTokenWithFetch(): Promise<ICredentials>;
22
27
  /**
23
28
  * 認証情報を手動でセットする
24
29
  */
@@ -36,11 +41,11 @@ export default class RefreshTokenClient {
36
41
  * APIリクエストを投げる
37
42
  * 認証エラー(401,403)であれば自動的に一度だけアクセストークンをリフレッシュします。
38
43
  */
39
- request(options: request.OptionsWithUri, expectedStatusCodes: number[]): Promise<any>;
44
+ request(options: IRequestOptions, expectedStatusCodes: number[]): Promise<any>;
40
45
  /**
41
46
  * 認証情報が適切である前提でAPIリクエストを投げる
42
47
  */
43
- protected makeRequest(options: request.OptionsWithUri, expectedStatusCodes: number[]): Promise<any>;
48
+ protected makeRequest(options: IRequestOptions, expectedStatusCodes: number[]): Promise<any>;
44
49
  /**
45
50
  * 認証情報を更新する
46
51
  */
@@ -9,11 +9,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.RefreshTokenClient = void 0;
12
13
  const createDebug = require("debug");
13
14
  const http_status_1 = require("http-status");
14
15
  const request = require("request");
15
16
  const transporters_1 = require("../transporters");
16
17
  const debug = createDebug('coa-service:auth:refreshTokenClient');
18
+ const TIMEOUT = 10000;
17
19
  /**
18
20
  * リフレッシュトークン認証クライアント
19
21
  */
@@ -25,7 +27,7 @@ class RefreshTokenClient {
25
27
  /**
26
28
  * トークンエンドポイントからアクセストークンを取得します。
27
29
  */
28
- getToken() {
30
+ getTokenWithRequest() {
29
31
  return __awaiter(this, void 0, void 0, function* () {
30
32
  return new Promise((resolve, reject) => {
31
33
  debug('requesting an access token...');
@@ -64,6 +66,77 @@ class RefreshTokenClient {
64
66
  });
65
67
  });
66
68
  }
69
+ /**
70
+ * トークンエンドポイントからアクセストークンを取得します。
71
+ */
72
+ getTokenWithFetch() {
73
+ return __awaiter(this, void 0, void 0, function* () {
74
+ debug('requesting an access token...');
75
+ try {
76
+ const params = new URLSearchParams({ refresh_token: String(this.options.refreshToken) });
77
+ const res = yield fetch(`${this.options.endpoint}/token/access_token`, {
78
+ method: 'POST',
79
+ headers: {
80
+ 'Content-Type': 'application/x-www-form-urlencoded'
81
+ },
82
+ body: params,
83
+ signal: AbortSignal.timeout(TIMEOUT)
84
+ });
85
+ let body;
86
+ try {
87
+ body = yield res.json();
88
+ }
89
+ catch (error) {
90
+ // no op
91
+ }
92
+ debug('res.status:', res.status, 'body:', body);
93
+ switch (res.status) {
94
+ case http_status_1.OK:
95
+ this.credentials = body;
96
+ break;
97
+ default:
98
+ let err = new Error('Unexpected error occurred.');
99
+ if (body !== undefined && body !== null) {
100
+ if (typeof body === 'string') {
101
+ err = new Error(body);
102
+ }
103
+ else if (typeof body.message === 'string' && body.message.length > 0) {
104
+ // エラーレスポンスにメッセージがあった場合
105
+ err = new Error(body.message);
106
+ }
107
+ else if (body.status !== undefined && body.status !== 0) {
108
+ // エラーレスポンスにステータスがあった場合
109
+ err = new Error(body.status);
110
+ }
111
+ }
112
+ throw err;
113
+ }
114
+ }
115
+ catch (err) {
116
+ // tslint:disable-next-line:no-single-line-block-comment
117
+ /* istanbul ignore next */
118
+ if (err.name === 'TimeoutError') {
119
+ // tslint:disable-next-line:no-console
120
+ console.error('getTokenWithFetch: Timeout: It took more than 5 seconds to get the result!', err);
121
+ }
122
+ else if (err.name === 'AbortError') {
123
+ // tslint:disable-next-line:no-console
124
+ console.error('getTokenWithFetch: Fetch aborted by user action (browser stop button, closing tab, etc.', err);
125
+ }
126
+ else if (err.name === 'TypeError') {
127
+ // tslint:disable-next-line:no-console
128
+ console.error('getTokenWithFetch: AbortSignal.timeout() method is not supported', err);
129
+ }
130
+ else {
131
+ // A network error, or some other problem.
132
+ // tslint:disable-next-line:no-console
133
+ console.error(`getTokenWithFetch: Error: type: ${err.name}, message: ${err.message}`, err);
134
+ }
135
+ throw err;
136
+ }
137
+ return this.credentials;
138
+ });
139
+ }
67
140
  /**
68
141
  * 認証情報を手動でセットする
69
142
  */
@@ -135,6 +208,8 @@ class RefreshTokenClient {
135
208
  /* istanbul ignore else */
136
209
  if (error instanceof Error) {
137
210
  const statusCode = error.code;
211
+ // tslint:disable-next-line:no-single-line-block-comment
212
+ /* istanbul ignore else */
138
213
  if (statusCode === http_status_1.UNAUTHORIZED || statusCode === http_status_1.FORBIDDEN) {
139
214
  if (retry) {
140
215
  // 多くの場合、認証エラーは、トークンの期限が原因なので、一度だけリフレッシュするのは有効なはず。
@@ -164,7 +239,8 @@ class RefreshTokenClient {
164
239
  // tslint:disable-next-line:prefer-function-over-method
165
240
  makeRequest(options, expectedStatusCodes) {
166
241
  return __awaiter(this, void 0, void 0, function* () {
167
- const transporter = new transporters_1.DefaultTransporter(expectedStatusCodes);
242
+ // const transporter = new DefaultTransporter(expectedStatusCodes);
243
+ const transporter = new transporters_1.FetchTransporter(expectedStatusCodes);
168
244
  return transporter.request(options);
169
245
  });
170
246
  }
@@ -174,12 +250,13 @@ class RefreshTokenClient {
174
250
  refreshToken(__) {
175
251
  return __awaiter(this, void 0, void 0, function* () {
176
252
  debug('refreshing an access token...');
177
- return this.getToken();
253
+ // return this.getTokenWithRequest();
254
+ return this.getTokenWithFetch();
178
255
  });
179
256
  }
180
257
  }
181
- exports.default = RefreshTokenClient;
182
258
  /**
183
259
  * アクセストークンの有効期限までの猶予時間初期値
184
260
  */
185
261
  RefreshTokenClient.DEFAULT_SPARE_TIME_IN_MILLISECONDS = 60000;
262
+ exports.RefreshTokenClient = RefreshTokenClient;
package/lib/index.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  import * as factory from './factory';
5
5
  import { MasterService } from './service/master';
6
6
  import { ReserveService } from './service/reserve';
7
- import RefreshTokenClient from './auth/refreshTokenClient';
7
+ import { RefreshTokenClient } from './auth/refreshTokenClient';
8
8
  export import factory = factory;
9
9
  export declare namespace auth {
10
10
  /**
package/lib/index.js CHANGED
@@ -14,7 +14,7 @@ var auth;
14
14
  /**
15
15
  * リフレッシュトークン認証クライアント
16
16
  */
17
- class RefreshToken extends refreshTokenClient_1.default {
17
+ class RefreshToken extends refreshTokenClient_1.RefreshTokenClient {
18
18
  }
19
19
  auth.RefreshToken = RefreshToken;
20
20
  })(auth = exports.auth || (exports.auth = {}));
package/lib/service.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as request from 'request';
2
- import RefreshTokenClient from './auth/refreshTokenClient';
2
+ import { IRequestOptions, RefreshTokenClient } from './auth/refreshTokenClient';
3
3
  /**
4
4
  * service constructor options
5
5
  */
@@ -7,15 +7,16 @@ export interface IOptions {
7
7
  endpoint: string;
8
8
  auth: RefreshTokenClient;
9
9
  }
10
+ export type ICustomRequestOption = Pick<request.CoreOptions, 'timeout'>;
10
11
  /**
11
12
  * base service class
12
13
  */
13
14
  export declare class Service {
14
15
  options: IOptions;
15
16
  requestOptions: request.CoreOptions;
16
- constructor(options: IOptions, requestOptions?: request.CoreOptions);
17
+ constructor(options: IOptions, requestOptions?: ICustomRequestOption);
17
18
  /**
18
19
  * Create and send request to API
19
20
  */
20
- request(options: request.OptionsWithUri, expectedStatusCodes: number[]): Promise<any>;
21
+ request(options: IRequestOptions, expectedStatusCodes: number[]): Promise<any>;
21
22
  }
@@ -1,20 +1,26 @@
1
1
  import * as request from 'request';
2
+ /**
3
+ * リクエスト成功の場合のレスポンス本文のstatus属性の値
4
+ * 失敗の場合はstring型だが、成功の場合のみnumber型が返却されるので注意すること。
5
+ */
6
+ export declare const RESPONSE_BODY_STAUS_SUCCESS = 0;
7
+ export type IRequestOptions = Pick<request.OptionsWithUri, 'uri' | 'method' | 'qs' | 'auth' | 'headers' | 'baseUrl' | 'timeout'>;
2
8
  /**
3
9
  * transporter abstract class
4
10
  * トランスポーター抽象クラス
5
11
  */
6
12
  export declare abstract class Transporter {
7
- abstract request(options: request.OptionsWithUri): Promise<any>;
13
+ abstract request(options: IRequestOptions): Promise<any>;
8
14
  }
9
- export declare type IBodyResponseCallback = Promise<any>;
15
+ export type IBodyResponseCallback = Promise<any>;
10
16
  /**
11
17
  * COAServiceError
12
18
  */
13
19
  export declare class COAServiceError extends Error {
14
20
  code: number;
15
21
  status: string;
16
- requestOptions: request.OptionsWithUri | undefined;
17
- constructor(code: number, status: string, message?: string, requestOptions?: request.OptionsWithUri);
22
+ requestOptions: IRequestOptions | undefined;
23
+ constructor(code: number, status: string, message?: string, requestOptions?: IRequestOptions);
18
24
  }
19
25
  /**
20
26
  * DefaultTransporter
@@ -29,11 +35,34 @@ export declare class DefaultTransporter implements Transporter {
29
35
  /**
30
36
  * Configures request options before making a request.
31
37
  */
32
- static CONFIGURE(options: request.OptionsWithUri): request.OptionsWithUri;
38
+ static CONFIGURE(options: IRequestOptions): IRequestOptions;
39
+ /**
40
+ * Makes a request with given options and invokes callback.
41
+ */
42
+ request(options: IRequestOptions): Promise<any>;
43
+ /**
44
+ * Wraps the response callback.
45
+ */
46
+ private wrapCallback;
47
+ }
48
+ /**
49
+ * FetchTransporter
50
+ */
51
+ export declare class FetchTransporter implements Transporter {
52
+ /**
53
+ * Default user agent.
54
+ */
55
+ static readonly USER_AGENT: string;
56
+ expectedStatusCodes: number[];
57
+ constructor(expectedStatusCodes: number[]);
58
+ /**
59
+ * Configures request options before making a request.
60
+ */
61
+ static CONFIGURE(options: IRequestOptions): IRequestOptions;
33
62
  /**
34
63
  * Makes a request with given options and invokes callback.
35
64
  */
36
- request(options: request.OptionsWithUri): Promise<any>;
65
+ request(options: IRequestOptions): Promise<any>;
37
66
  /**
38
67
  * Wraps the response callback.
39
68
  */
@@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.DefaultTransporter = exports.COAServiceError = exports.Transporter = void 0;
12
+ exports.FetchTransporter = exports.DefaultTransporter = exports.COAServiceError = exports.Transporter = exports.RESPONSE_BODY_STAUS_SUCCESS = void 0;
13
13
  // tslint:disable:max-classes-per-file
14
14
  /**
15
15
  * transporters
@@ -24,7 +24,7 @@ const pkg = require('../package.json');
24
24
  * リクエスト成功の場合のレスポンス本文のstatus属性の値
25
25
  * 失敗の場合はstring型だが、成功の場合のみnumber型が返却されるので注意すること。
26
26
  */
27
- const RESPONSE_BODY_STAUS_SUCCESS = 0;
27
+ exports.RESPONSE_BODY_STAUS_SUCCESS = 0;
28
28
  /**
29
29
  * transporter abstract class
30
30
  * トランスポーター抽象クラス
@@ -122,7 +122,7 @@ class DefaultTransporter {
122
122
  }
123
123
  else {
124
124
  // HTTPステータスコード2xxでも、レスポンス本文のステータスが0でなければBadRequest
125
- if (body.status !== undefined && body.status !== RESPONSE_BODY_STAUS_SUCCESS) {
125
+ if (body.status !== undefined && body.status !== exports.RESPONSE_BODY_STAUS_SUCCESS) {
126
126
  err = new COAServiceError(response.statusCode, body.status, body.message, requestOptions);
127
127
  }
128
128
  else {
@@ -143,8 +143,118 @@ class DefaultTransporter {
143
143
  throw err;
144
144
  }
145
145
  }
146
- exports.DefaultTransporter = DefaultTransporter;
147
146
  /**
148
147
  * Default user agent.
149
148
  */
150
149
  DefaultTransporter.USER_AGENT = `coa-service/${pkg.version}`;
150
+ exports.DefaultTransporter = DefaultTransporter;
151
+ /**
152
+ * FetchTransporter
153
+ */
154
+ class FetchTransporter {
155
+ constructor(expectedStatusCodes) {
156
+ this.expectedStatusCodes = expectedStatusCodes;
157
+ }
158
+ /**
159
+ * Configures request options before making a request.
160
+ */
161
+ static CONFIGURE(options) {
162
+ // set transporter user agent
163
+ options.headers = (options.headers !== undefined) ? options.headers : {};
164
+ // tslint:disable-next-line:no-single-line-block-comment
165
+ /* istanbul ignore else */
166
+ if (!options.headers['User-Agent']) {
167
+ options.headers['User-Agent'] = DefaultTransporter.USER_AGENT;
168
+ }
169
+ else if (options.headers['User-Agent'].indexOf(DefaultTransporter.USER_AGENT) === -1) {
170
+ options.headers['User-Agent'] = `${options.headers['User-Agent']} ${DefaultTransporter.USER_AGENT}`;
171
+ }
172
+ else {
173
+ // no operation
174
+ }
175
+ return options;
176
+ }
177
+ /**
178
+ * Makes a request with given options and invokes callback.
179
+ */
180
+ request(options) {
181
+ var _a;
182
+ return __awaiter(this, void 0, void 0, function* () {
183
+ const requestOptions = FetchTransporter.CONFIGURE(options);
184
+ debug('requesting...', requestOptions);
185
+ const input = `${requestOptions.baseUrl}${requestOptions.uri}?${(new URLSearchParams(requestOptions.qs)).toString()}`;
186
+ const accessToken = (_a = requestOptions.auth) === null || _a === void 0 ? void 0 : _a.bearer;
187
+ debug('fetching...', input);
188
+ return fetch(input, Object.assign({ method: requestOptions.method, headers: Object.assign(Object.assign({}, requestOptions.headers), (typeof accessToken === 'string') ? { Authorization: `Bearer ${accessToken}` } /* istanbul ignore else */ : undefined) }, (typeof requestOptions.timeout === 'number') ? { signal: AbortSignal.timeout(requestOptions.timeout) } : undefined))
189
+ .then((res) => __awaiter(this, void 0, void 0, function* () { return this.wrapCallback(res, requestOptions); }));
190
+ });
191
+ }
192
+ /**
193
+ * Wraps the response callback.
194
+ */
195
+ wrapCallback(res, options) {
196
+ return __awaiter(this, void 0, void 0, function* () {
197
+ const requestOptions = { uri: options.uri };
198
+ let err = new COAServiceError(http_status_1.INTERNAL_SERVER_ERROR, '', 'An unexpected error occurred.', requestOptions);
199
+ debug('fetch processed. res.status:', res.status, 'content-type:', res.headers.get('content-type'));
200
+ let body = {};
201
+ try {
202
+ if (res.headers.get('content-type') === 'text/plain') {
203
+ body = yield res.text();
204
+ }
205
+ else {
206
+ body = yield res.json();
207
+ }
208
+ }
209
+ catch (error) {
210
+ // no op
211
+ }
212
+ // tslint:disable-next-line:no-single-line-block-comment
213
+ /* istanbul ignore else */
214
+ if (res.status !== undefined) {
215
+ if (this.expectedStatusCodes.indexOf(res.status) < 0) {
216
+ if (typeof body === 'string') {
217
+ // Consider all 4xx and 5xx responses errors.
218
+ err = new COAServiceError(res.status, '', body, requestOptions);
219
+ }
220
+ else {
221
+ // エラーレスポンスにステータスがあった場合
222
+ // tslint:disable-next-line:no-single-line-block-comment
223
+ /* istanbul ignore else */
224
+ if (body.status !== undefined) {
225
+ err = new COAServiceError(res.status, body.status, body.message, requestOptions);
226
+ }
227
+ else {
228
+ // no operation
229
+ }
230
+ }
231
+ }
232
+ else {
233
+ // HTTPステータスコード2xxでも、レスポンス本文のステータスが0でなければBadRequest
234
+ if (body.status !== undefined && body.status !== exports.RESPONSE_BODY_STAUS_SUCCESS) {
235
+ err = new COAServiceError(res.status, body.status, body.message, requestOptions);
236
+ }
237
+ else {
238
+ if (res.status === http_status_1.NO_CONTENT) {
239
+ // consider 204
240
+ return;
241
+ }
242
+ else {
243
+ // consider 200,201
244
+ return body;
245
+ }
246
+ }
247
+ }
248
+ }
249
+ else {
250
+ // no operation
251
+ }
252
+ throw err;
253
+ });
254
+ }
255
+ }
256
+ /**
257
+ * Default user agent.
258
+ */
259
+ FetchTransporter.USER_AGENT = `coa-service/${pkg.version}`;
260
+ exports.FetchTransporter = FetchTransporter;