-
Notifications
You must be signed in to change notification settings - Fork 26
/
ApiClient.js
360 lines (341 loc) · 13.5 KB
/
ApiClient.js
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
import request from "superagent";
import { v4 as uuidv4 } from "uuid";
import packageJson from "../../package.json";
import Encryption from "./Encryption";
import HyperwalletVerificationDocument from "../models/HyperwalletVerificationDocument";
import HyperwalletVerificationDocumentReason from "../models/HyperwalletVerificationDocumentReason";
/**
* The callback interface for api calls
*
* @typedef {function} api-callback
* @param {Object[]} [errors] - In case of an error an array with error objects otherwise undefined
* @param {string} [errors[].fieldName] - The field name (if error is caused by a particular field)
* @param {string} errors[].message - The error message
* @param {string} errors[].code - The error code
* @param {Object} data - The rest response body
* @param {Object} res - The raw superagent response object
*/
/**
* The Hyperwallet API Client
*/
export default class ApiClient {
/**
* Create a instance of the API client
*
* @param {string} username - The API username
* @param {string} password - The API password
* @param {string} server - The API server to connect to
* @param {string} encryptionData - The API encryption data
*/
constructor(username, password, server, encryptionData) {
/**
* The API username
*
* @type {string}
* @protected
*/
this.username = username;
/**
* The API password
*
* @type {string}
* @protected
*/
this.password = password;
/**
* The API server to connect to
* @type {string}
* @protected
*/
this.server = server;
/**
* The Node SDK Version number
*
* @type {string}
* @protected
*/
this.version = packageJson.version;
/**
* The flag shows if encryption is enabled
*
* @type {boolean}
* @protected
*/
this.isEncrypted = false;
this.contextId = uuidv4();
if (encryptionData && encryptionData.clientPrivateKeySetPath && encryptionData.hyperwalletKeySetPath) {
this.isEncrypted = true;
this.clientPrivateKeySetPath = encryptionData.clientPrivateKeySetPath;
this.hyperwalletKeySetPath = encryptionData.hyperwalletKeySetPath;
this.encryption = new Encryption(this.clientPrivateKeySetPath, this.hyperwalletKeySetPath);
}
}
/**
* Format response to documents model before passing to callback
*
* @param {Object} res - Response object
*
*/
static formatResForCallback(res) {
const retRes = res;
if (res && res.body) {
const retBody = res.body;
const { documents } = retBody;
if (documents && documents.length > 0) {
const documentsArr = [];
documents.forEach((dVal) => {
const doc = dVal;
if (dVal.reasons && dVal.reasons.length > 0) {
const reasonsArr = [];
dVal.reasons.forEach((rVal) => {
reasonsArr.push(new HyperwalletVerificationDocumentReason(rVal));
});
doc.reasons = reasonsArr;
}
documentsArr.push(new HyperwalletVerificationDocument(doc));
});
retBody.documents = documentsArr;
retRes.body = retBody;
}
}
return retRes;
}
/**
* Do a POST call to the Hyperwallet API server
*
* @param {string} partialUrl - The api endpoint to call (gets prefixed by `server` and `/rest/v4/`)
* @param {Object} data - The data to send to the server
* @param {Object} params - Query parameters to send in this call
* @param {api-callback} callback - The callback for this call
*/
doPost(partialUrl, data, params, callback) {
let contentType = "application/json";
let accept = "application/json";
let requestDataPromise = new Promise(resolve => resolve(data));
if (this.isEncrypted) {
contentType = "application/jose+json";
accept = "application/jose+json";
ApiClient.createJoseJsonParser();
requestDataPromise = this.encryption.encrypt(data);
}
requestDataPromise.then((requestData) => {
request
.post(`${this.server}/rest/v4/${partialUrl}`)
.auth(this.username, this.password)
.set("User-Agent", `Hyperwallet Node SDK v${this.version}`)
.set("x-sdk-version", this.version)
.set("x-sdk-type", "NodeJS")
.set("x-sdk-contextId", this.contextId)
.type(contentType)
.accept(accept)
.query(params)
.send(requestData)
.end(this.wrapCallback("POST", callback));
}).catch(() => callback([{ message: "Failed to encrypt body for POST request" }], undefined, undefined));
}
/**
* Do a PUT call to the Hyperwallet API server to upload documents
*
* @param {string} partialUrl - The api endpoint to call (gets prefixed by `server` and `/rest/v4/`)
* @param {Object} data - The data to send to the server
* @param {api-callback} callback - The callback for this call
*/
doPutMultipart(partialUrl, data, callback) {
let contentType = "multipart/form-data";
let accept = "application/json";
/* eslint-disable no-unused-vars */
const keys = Object.keys(data);
/* eslint-enable no-unused-vars */
let requestDataPromise = new Promise(resolve => resolve(data));
if (this.isEncrypted) {
contentType = "multipart/form-data";
accept = "application/jose+json";
ApiClient.createJoseJsonParser();
requestDataPromise = this.encryption.encrypt(data);
}
requestDataPromise.then(() => {
const req = request
.put(`${this.server}/rest/v4/${partialUrl}`)
.auth(this.username, this.password)
.set("User-Agent", `Hyperwallet Node SDK v${this.version}`)
.set("x-sdk-version", this.version)
.set("x-sdk-type", "NodeJS")
.set("x-sdk-contextId", this.contextId)
.type(contentType)
.accept(accept);
keys.forEach((key) => {
if (key === "data") {
req.field(key, JSON.stringify(data[key]));
} else {
req.attach(key, data[key]);
}
});
req.end(this.wrapCallback("PUT", callback));
}).catch(err => callback(err, undefined, undefined));
}
/**
* Do a PUT call to the Hyperwallet API server
*
* @param {string} partialUrl - The api endpoint to call (gets prefixed by server and /rest/v4/)
* @param {Object} data - The data to send to the server
* @param {Object} params - Query parameters to send in this call
* @param {api-callback} callback - The callback for this call
*/
doPut(partialUrl, data, params, callback) {
let contentType = "application/json";
let accept = "application/json";
let requestDataPromise = new Promise(resolve => resolve(data));
if (this.isEncrypted) {
contentType = "application/jose+json";
accept = "application/jose+json";
ApiClient.createJoseJsonParser();
requestDataPromise = this.encryption.encrypt(data);
}
requestDataPromise.then((requestData) => {
request
.put(`${this.server}/rest/v4/${partialUrl}`)
.auth(this.username, this.password)
.set("User-Agent", `Hyperwallet Node SDK v${this.version}`)
.set("x-sdk-version", this.version)
.set("x-sdk-type", "NodeJS")
.set("x-sdk-contextId", this.contextId)
.type(contentType)
.accept(accept)
.query(params)
.send(requestData)
.end(this.wrapCallback("PUT", callback));
}).catch(() => callback([{ message: "Failed to encrypt body for PUT request" }], undefined, undefined));
}
/**
* Do a GET call to the Hyperwallet API server
*
* @param {string} partialUrl - The api endpoint to call (gets prefixed by `server` and `/rest/v4/`)
* @param {Object} params - Query parameters to send in this call
* @param {api-callback} callback - The callback for this call
*/
doGet(partialUrl, params, callback) {
let contentType = "application/json";
let accept = "application/json";
if (this.isEncrypted) {
contentType = "application/jose+json";
accept = "application/jose+json";
ApiClient.createJoseJsonParser();
}
request
.get(`${this.server}/rest/v4/${partialUrl}`)
.auth(this.username, this.password)
.set("User-Agent", `Hyperwallet Node SDK v${this.version}`)
.set("x-sdk-version", this.version)
.set("x-sdk-type", "NodeJS")
.set("x-sdk-contextId", this.contextId)
.type(contentType)
.accept(accept)
.query(params)
.end(this.wrapCallback("GET", callback));
}
/**
* Wrap a callback to process possible API and network errors
*
* @param {string} httpMethod - The http method that is currently processing
* @param {api-callback} callback - The final callback
* @returns {function(err: Object, res: Object)} - The super agent callback
*
* @private
*/
wrapCallback(httpMethod, callback = () => null) {
return (err, res) => {
const contentTypeHeader = res && res.header ? res.header["content-type"] : undefined;
if (!err) {
const expectedContentType = (this.isEncrypted) ? "application/jose+json" : "application/json";
if (res && res.status !== 204 && contentTypeHeader && !contentTypeHeader.includes(expectedContentType)) {
callback([{
message: "Invalid Content-Type specified in Response Header",
}], res ? res.body : undefined, res);
return;
}
}
if (this.isEncrypted && contentTypeHeader && contentTypeHeader.includes("application/jose+json")
&& res.body && !ApiClient.isEmptyResponseBody(res.body)) {
this.processEncryptedResponse(httpMethod, err, res.body, callback);
} else {
this.processNonEncryptedResponse(err, res, callback);
}
};
}
/**
* Process non encrypted response from server
*
* @param {Object} err - Error object
* @param {Object} res - Response object
* @param {api-callback} callback - The final callback
*
* @private
*/
processNonEncryptedResponse(err, res, callback) {
if (!err) {
const formattedRes = ApiClient.formatResForCallback(res);
callback(undefined, formattedRes.body, formattedRes);
return;
}
let errors = [
{
message: err.status ? err.message : `Could not communicate with ${this.server}`,
code: err.status ? err.status.toString() : "COMMUNICATION_ERROR",
},
];
if (res && res.body && res.body.errors) {
// eslint-disable-next-line prefer-destructuring
errors = res.body.errors;
}
callback(errors, res ? res.body : undefined, res);
}
/**
* Process encrypted response from server
*
* @param {string} httpMethod - The http method that is currently processing
* @param {Object} err - Error object
* @param {Object} res - Response object
* @param {api-callback} callback - The final callback
*
* @private
*/
processEncryptedResponse(httpMethod, err, res, callback) {
this.encryption.decrypt(res)
.then((decryptedData) => {
const responseBody = JSON.parse(decryptedData.payload.toString());
if (responseBody.errors) {
const responseWithErrors = {};
responseWithErrors.body = responseBody;
this.processNonEncryptedResponse(responseBody, responseWithErrors, callback);
} else {
const formattedRes = ApiClient.formatResForCallback({ body: responseBody });
callback(undefined, formattedRes.body, decryptedData);
}
})
.catch(() => callback([{ message: `Failed to decrypt response for ${httpMethod} request` }], res, res));
}
/**
* Creates response body parser for application/jose+json content-type
*
* @private
*/
static createJoseJsonParser() {
request.parse["application/jose+json"] = (res, callback) => {
let data = "";
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
callback(null, data);
});
};
}
/**
* Helper function to check if the response body is an empty object
*
* @private
*/
static isEmptyResponseBody(body) {
return Object.keys(body).length === 0 && Object.getPrototypeOf(body) === Object.prototype;
}
}