-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
RestAPI.ts
338 lines (274 loc) · 9.33 KB
/
RestAPI.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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { RestClient } from './RestClient';
import {
Amplify,
ConsoleLogger as Logger,
Credentials,
} from '@aws-amplify/core';
import { ApiInfo } from './types';
const logger = new Logger('RestAPI');
/**
* Export Cloud Logic APIs
*/
export class RestAPIClass {
/**
* @private
*/
private _options;
private _api: RestClient = null;
Credentials = Credentials;
/**
* Initialize Rest API with AWS configuration
* @param {Object} options - Configuration object for API
*/
constructor(options) {
this._options = options;
logger.debug('API Options', this._options);
}
public getModuleName() {
return 'RestAPI';
}
/**
* Configure API part with aws configurations
* @param {Object} config - Configuration of the API
* @return {Object} - The current configuration
*/
configure(options) {
const { API = {}, ...otherOptions } = options || {};
let opt = { ...otherOptions, ...API };
logger.debug('configure Rest API', { opt });
if (opt['aws_project_region']) {
if (opt['aws_cloud_logic_custom']) {
const custom = opt['aws_cloud_logic_custom'];
opt.endpoints =
typeof custom === 'string' ? JSON.parse(custom) : custom;
}
opt = Object.assign({}, opt, {
region: opt['aws_project_region'],
header: {},
});
}
if (Array.isArray(opt.endpoints)) {
// Check if endpoints has custom_headers and validate if is a function
opt.endpoints.forEach(endpoint => {
if (
typeof endpoint.custom_header !== 'undefined' &&
typeof endpoint.custom_header !== 'function'
) {
logger.warn(
'Rest API ' + endpoint.name + ', custom_header should be a function'
);
endpoint.custom_header = undefined;
}
});
} else if (this._options && Array.isArray(this._options.endpoints)) {
opt.endpoints = this._options.endpoints;
} else {
opt.endpoints = [];
}
this._options = Object.assign({}, this._options, opt);
this.createInstance();
return this._options;
}
/**
* Create an instance of API for the library
* @return - A promise of true if Success
*/
createInstance() {
logger.debug('create Rest API instance');
this._api = new RestClient(this._options);
// Share Amplify instance with client for SSR
this._api.Credentials = this.Credentials;
return true;
}
/**
* Make a GET request
* @param {string} apiName - The api name of the request
* @param {string} path - The path of the request
* @param {json} [init] - Request extra params
* @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
*/
get(apiName, path, init): Promise<any> {
try {
const apiInfo = this.getEndpointInfo(apiName, path);
const cancellableToken = this._api.getCancellableToken();
const initParams = Object.assign({}, init);
initParams.cancellableToken = cancellableToken;
const responsePromise = this._api.get(apiInfo, initParams);
this._api.updateRequestToBeCancellable(responsePromise, cancellableToken);
return responsePromise;
} catch (err) {
return Promise.reject(err.message);
}
}
/**
* Make a POST request
* @param {string} apiName - The api name of the request
* @param {string} path - The path of the request
* @param {json} [init] - Request extra params
* @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
*/
post(apiName, path, init): Promise<any> {
try {
const apiInfo = this.getEndpointInfo(apiName, path);
const cancellableToken = this._api.getCancellableToken();
const initParams = Object.assign({}, init);
initParams.cancellableToken = cancellableToken;
const responsePromise = this._api.post(apiInfo, initParams);
this._api.updateRequestToBeCancellable(responsePromise, cancellableToken);
return responsePromise;
} catch (err) {
return Promise.reject(err.message);
}
}
/**
* Make a PUT request
* @param {string} apiName - The api name of the request
* @param {string} path - The path of the request
* @param {json} [init] - Request extra params
* @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
*/
put(apiName, path, init): Promise<any> {
try {
const apiInfo = this.getEndpointInfo(apiName, path);
const cancellableToken = this._api.getCancellableToken();
const initParams = Object.assign({}, init);
initParams.cancellableToken = cancellableToken;
const responsePromise = this._api.put(apiInfo, initParams);
this._api.updateRequestToBeCancellable(responsePromise, cancellableToken);
return responsePromise;
} catch (err) {
return Promise.reject(err.message);
}
}
/**
* Make a PATCH request
* @param {string} apiName - The api name of the request
* @param {string} path - The path of the request
* @param {json} [init] - Request extra params
* @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
*/
patch(apiName, path, init): Promise<any> {
try {
const apiInfo = this.getEndpointInfo(apiName, path);
const cancellableToken = this._api.getCancellableToken();
const initParams = Object.assign({}, init);
initParams.cancellableToken = cancellableToken;
const responsePromise = this._api.patch(apiInfo, initParams);
this._api.updateRequestToBeCancellable(responsePromise, cancellableToken);
return responsePromise;
} catch (err) {
return Promise.reject(err.message);
}
}
/**
* Make a DEL request
* @param {string} apiName - The api name of the request
* @param {string} path - The path of the request
* @param {json} [init] - Request extra params
* @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
*/
del(apiName, path, init): Promise<any> {
try {
const apiInfo = this.getEndpointInfo(apiName, path);
const cancellableToken = this._api.getCancellableToken();
const initParams = Object.assign({}, init);
initParams.cancellableToken = cancellableToken;
const responsePromise = this._api.del(apiInfo, initParams);
this._api.updateRequestToBeCancellable(responsePromise, cancellableToken);
return responsePromise;
} catch (err) {
return Promise.reject(err.message);
}
}
/**
* Make a HEAD request
* @param {string} apiName - The api name of the request
* @param {string} path - The path of the request
* @param {json} [init] - Request extra params
* @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
*/
head(apiName, path, init): Promise<any> {
try {
const apiInfo = this.getEndpointInfo(apiName, path);
const cancellableToken = this._api.getCancellableToken();
const initParams = Object.assign({}, init);
initParams.cancellableToken = cancellableToken;
const responsePromise = this._api.head(apiInfo, initParams);
this._api.updateRequestToBeCancellable(responsePromise, cancellableToken);
return responsePromise;
} catch (err) {
return Promise.reject(err.message);
}
}
/**
* Checks to see if an error thrown is from an api request cancellation
* @param {any} error - Any error
* @return {boolean} - A boolean indicating if the error was from an api request cancellation
*/
isCancel(error) {
return this._api.isCancel(error);
}
/**
* Cancels an inflight request
* @param {any} request - request to cancel
* @return {boolean} - A boolean indicating if the request was cancelled
*/
cancel(request: Promise<any>, message?: string) {
return this._api.cancel(request, message);
}
/**
* Check if the request has a corresponding cancel token in the WeakMap.
* @params request - The request promise
* @return if the request has a corresponding cancel token.
*/
hasCancelToken(request: Promise<any>) {
return this._api.hasCancelToken(request);
}
/**
* Getting endpoint for API
* @param {string} apiName - The name of the api
* @return {string} - The endpoint of the api
*/
async endpoint(apiName) {
return this._api.endpoint(apiName);
}
/**
* Getting endpoint info for API
* @param {string} apiName - The name of the api
* @param {string} path - The path of the api that is going to accessed
* @return {ApiInfo} - The endpoint information for that api-name
*/
private getEndpointInfo(apiName: string, path: string): ApiInfo {
const cloud_logic_array = this._options.endpoints;
if (!Array.isArray(cloud_logic_array)) {
throw new Error(`API category not configured`);
}
const apiConfig = cloud_logic_array.find(api => api.name === apiName);
if (!apiConfig) {
throw new Error(`API ${apiName} does not exist`);
}
const response: ApiInfo = {
endpoint: apiConfig.endpoint + path,
};
if (typeof apiConfig.region === 'string') {
response.region = apiConfig.region;
} else if (typeof this._options.region === 'string') {
response.region = this._options.region;
}
if (typeof apiConfig.service === 'string') {
response.service = apiConfig.service || 'execute-api';
} else {
response.service = 'execute-api';
}
if (typeof apiConfig.custom_header === 'function') {
response.custom_header = apiConfig.custom_header;
} else {
response.custom_header = undefined;
}
return response;
}
}
export const RestAPI = new RestAPIClass(null);
Amplify.register(RestAPI);