-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathbaseRequests.js
More file actions
448 lines (399 loc) · 18.4 KB
/
Copy pathbaseRequests.js
File metadata and controls
448 lines (399 loc) · 18.4 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
'use strict';
const safeStringify = require('fast-safe-stringify');
const http = require('http');
const https = require('https');
const { RESOURCES, ISO_20022_HEADER_PART } = require('../constants');
const {
bodyStringifier,
buildUrl,
defineApiType,
formatEndpointOrDefault,
ResponseType,
throwOrJson,
} = require('./common');
const request = require('../request');
const { ApiType, ApiTransformer } = require('./apiTransformer');
const JwsSigner = require('../jws').signer;
/**
*
* @class BaseRequests
* @description BaseRequests is a 'mojaloop aware' base class for making mojaloop requests
* it contains all of the common bits that a Mojaloop client library needs to implement
* such as `jws`, `tls`, `mojaloop endpoints`, etc, and exposes functions for `_get()`,
* `_post()`, and `_put()` requests
*/
class BaseRequests {
/**
* @function constructor
* @param {Object} config - The Config Object
* @param {Object} config.logger Logging function
* @param {Object} config.tls The tls config object
* @param {string} config.dfspId The `FSPID` of _this_ DFSP/Participant
* @param {boolean} config.jwsSign If `true`, then requests will be JWS signed
* @param {boolean | undefined} config.jwsSignPutParties Optional. If undefined,
* it will default to the value of `config.jwsSign`
* @param {string | undefined} config.jwsSigningKey Optional. The jwsSigningKey
* to use. Required if `jwsSign === true`
* @param {Object | undefined} config.wso2 Optional. The wso2Auth object and
* number indicating how many times to retry a request that fails authorization.
* Example: { auth, retryWso2AuthFailureTimes: 1 }
*/
constructor(config) {
this.logger = config.logger;
// FSPID of THIS DFSP
this.dfspId = config.dfspId;
// make sure we always have an api type set (default to FSPIOP)
this.apiType = config.apiType || ApiType.FSPIOP;
// MojaloopRequests will always have a request transformer.
// We will use this transformer to reform requests from FSPIOP bodies/headers to alternatives
// if config.apiType is not 'fspiop' e.g. 'iso20022' will translate requests to mojaloop ISO formats.
// note that this is extensible for other future API flavours
this._apiTransformer = new ApiTransformer({
logger: this.logger,
apiType: this.apiType,
});
if (config.tls.enabled) {
this.agent = new https.Agent({
...config.tls.creds,
keepAlive: true
});
this.transportScheme = 'https';
}
else {
this.agent = http.globalAgent;
this.transportScheme = 'http';
}
// flag to turn jws signing on/off
this.jwsSign = config.jwsSign;
// if no jwsSignPutParties config is supplied it inherits the value of config.jwsSign
if (typeof (config.jwsSignPutParties) === 'undefined') {
this.jwsSignPutParties = config.jwsSign;
}
else {
this.jwsSignPutParties = config.jwsSignPutParties;
}
if (this.jwsSign) {
this.jwsSigner = new JwsSigner({
logger: config.logger,
signingKey: config.jwsSigningKey
});
}
this.resourceVersions = {
parties: {
contentVersion: '1.0',
acceptVersion: '1',
},
participants: {
contentVersion: '1.0',
acceptVersion: '1',
},
quotes: {
contentVersion: '1.0',
acceptVersion: '1',
},
bulkQuotes: {
contentVersion: '1.0',
acceptVersion: '1',
},
bulkTransfers: {
contentVersion: '1.0',
acceptVersion: '1',
},
transactionRequests: {
contentVersion: '1.0',
acceptVersion: '1',
},
authorizations: {
contentVersion: '1.0',
acceptVersion: '1',
},
[RESOURCES.fxQuotes]: {
contentVersion: '2.0',
acceptVersion: '2',
},
[RESOURCES.fxTransfers]: {
contentVersion: '2.0',
acceptVersion: '2',
},
transfers: {
contentVersion: '1.0',
acceptVersion: '1',
},
custom: {
contentVersion: '1.0',
acceptVersion: '1',
},
thirdparty: {
contentVersion: '1.0',
acceptVersion: '1',
},
services: {
contentVersion: '1.0',
acceptVersion: '1',
},
...config.resourceVersions
};
this.peerEndpoint = `${this.transportScheme}://${config.peerEndpoint}`;
this.resourceEndpoints = {
parties: formatEndpointOrDefault(config.alsEndpoint, this.transportScheme, this.peerEndpoint),
participants: formatEndpointOrDefault(config.alsEndpoint, this.transportScheme, this.peerEndpoint),
quotes: formatEndpointOrDefault(config.quotesEndpoint, this.transportScheme, this.peerEndpoint),
bulkQuotes: formatEndpointOrDefault(config.bulkQuotesEndpoint, this.transportScheme, this.peerEndpoint),
transfers: formatEndpointOrDefault(config.transfersEndpoint, this.transportScheme, this.peerEndpoint),
bulkTransfers: formatEndpointOrDefault(config.bulkTransfersEndpoint, this.transportScheme, this.peerEndpoint),
transactionRequests: formatEndpointOrDefault(config.transactionRequestsEndpoint, this.transportScheme, this.peerEndpoint),
authorizations: formatEndpointOrDefault(config.transactionRequestsEndpoint, this.transportScheme, this.peerEndpoint),
[RESOURCES.fxQuotes]: formatEndpointOrDefault(config.fxQuotesEndpoint, this.transportScheme, this.peerEndpoint),
[RESOURCES.fxTransfers]: formatEndpointOrDefault(config.fxTransfersEndpoint, this.transportScheme, this.peerEndpoint),
thirdparty: formatEndpointOrDefault(config.thirdpartyRequestsEndpoint, this.transportScheme, this.peerEndpoint),
services: formatEndpointOrDefault(config.servicesEndpoint, this.transportScheme, this.peerEndpoint),
};
this.wso2 = config.wso2 || {}; // default to empty object such that properties will be undefined
}
_request(opts, responseType) {
const __request = async (opts, responseType, attempts) => request(opts)
.then((res) => {
const retry =
res.statusCode === 401 &&
this.wso2.auth &&
attempts < this.wso2.retryWso2AuthFailureTimes;
if (retry) {
this.logger.isDebugEnabled && this.logger.debug('Received HTTP 401 for request. Attempting to retrieve a new token.');
const token = this.wso2.auth.refreshToken();
if (token) {
opts.headers['Authorization'] = `Bearer ${token}`;
} else {
const msg = 'Unable to retrieve WSO2 auth token';
this.logger.isDebugEnabled && this.logger.push({ attempts, opts, res }).debug(msg);
throw new Error(msg);
}
this.logger.isDebugEnabled && this.logger.push({ attempts, opts }).debug('Retrying request with new WSO2 token.');
return __request(opts, responseType, attempts + 1);
}
return res;
});
return __request(opts, responseType, 0)
.then((res) => (responseType === ResponseType.Mojaloop) ? throwOrJson(res) : res)
.catch((err) => {
const tryParse = (body) => {
try {
return JSON.parse(body);
} catch {
return undefined;
}
};
this.logger.isDebugEnabled && this.logger
.push({ opts: { ...opts, agent: '[REDACTED]' }, err, body: tryParse(opts.body) })
.debug('Error attempting request');
throw err;
});
}
/**
* @function _get
* @description
* Perform a HTTP GET request.
*
* **Note**: `config.jwsSign` is ignored here, as we don't JWS sign requests with no body
* @param {string} url - The url of the resource
* @param {string} resourceType - The 'type' of resource. Used to resolve the endpoint for the request
* @param {string | undefined} dest - The destination participant. Leave empty if participant is unknown (e.g. `GET /parties`)
* @param {*} headers - Optional additional headers
* @param {*} query - Optional query parameters
* @param {*} responseType - Optional, defaults to `Mojaloop`
*/
async _get(url, resourceType, dest, headers = {}, query = {}, responseType = ResponseType.Mojaloop) {
const reqOpts = {
method: 'GET',
uri: buildUrl(this._pickPeerEndpoint(resourceType), url),
headers: {
...this._buildHeaders('GET', resourceType, dest),
...headers,
},
qs: query,
agent: this.agent,
};
if (responseType === ResponseType.Stream) {
reqOpts.responseType = request.responseType.Stream;
}
// Note we do not JWS sign requests with no body i.e. GET requests
this.logger.isDebugEnabled && this.logger.debug(`Executing HTTP GET: ${safeStringify({ reqOpts: { ...reqOpts, agent: '[REDACTED]' }})}`);
return this._request(reqOpts, responseType);
}
/**
* @function _put
* @description
* Perform a HTTP PUT request.
*
* @param {string} url - The url of the resource
* @param {string} resourceType - The 'type' of resource, as defined in the Mojaloop specification
* @param {Object} body
* @param {string | undefined} dest - The destination participant. Leave empty if participant is unknown (e.g. `GET /parties`)
* @param {Object} headers - Optional additional headers
* @param {*} query - Optional query parameters
* @param {*} responseType - Optional, defaults to `Mojaloop`
* @param {Object} transformParams
*/
async _put(url, resourceType, body, dest, headers = {}, query = {},
responseType = ResponseType.Mojaloop, transformParams = {}) {
const reqOpts = {
method: 'PUT',
uri: buildUrl(this._pickPeerEndpoint(resourceType), url),
headers: {
...this._buildHeaders('PUT', resourceType, dest),
...headers,
},
body: body,
qs: query,
agent: this.agent,
};
// transform the request. This will only change the request if translation is required i.e. if this.apiType is not 'fspiop'
const transformed = await this._apiTransformer.transformOutboundRequest(resourceType, reqOpts.method, {
body: reqOpts.body,
headers: reqOpts.headers,
params: transformParams,
isError: transformParams.isError,
$context: transformParams.$context
});
reqOpts.body = transformed.body;
reqOpts.headers = { ...reqOpts.headers, ...transformed.headers };
if (responseType === ResponseType.Stream) {
reqOpts.responseType = request.responseType.Stream;
}
if ((responseType === ResponseType.Mojaloop) && this.jwsSign && (resourceType === 'parties' ? this.jwsSignPutParties : true)) {
this.jwsSigner.sign(reqOpts);
}
reqOpts.body = bodyStringifier(reqOpts.body);
this.logger.isDebugEnabled && this.logger.debug(`Executing HTTP PUT: ${safeStringify({ reqOpts: { ...reqOpts, agent: '[REDACTED]' }})}`);
return this._request(reqOpts, responseType);
}
/**
* @function _patch
* @description
* Perform a HTTP PATCH request.
*
* @param {string} url - The url of the resource
* @param {string} resourceType - The 'type' of resource, as defined in the Mojaloop specification
* @param body
* @param {string | undefined} dest - The destination participant. Leave empty if participant is unknown (e.g. `GET /parties`)
* @param {Object} headers - Optional additional headers
* @param {*} query - Optional query parameters
* @param {*} responseType - Optional, defaults to `Mojaloop`
* @param {Object} transformParams
*/
async _patch(url, resourceType, body, dest, headers = {}, query = {},
responseType = ResponseType.Mojaloop, transformParams = {}) {
const reqOpts = {
method: 'PATCH',
uri: buildUrl(this._pickPeerEndpoint(resourceType), url),
headers: {
...this._buildHeaders('PATCH', resourceType, dest),
...headers,
},
body: body,
qs: query,
agent: this.agent,
};
// transform the request. This will only change the request if translation is required i.e. if this.apiType is not 'fspiop'
const transformed = await this._apiTransformer.transformOutboundRequest(resourceType, reqOpts.method,
{ body: reqOpts.body, headers: reqOpts.headers, params: transformParams });
reqOpts.body = transformed.body;
reqOpts.headers = { ...reqOpts.headers, ...transformed.headers };
if ((responseType === ResponseType.Mojaloop) && this.jwsSign) {
this.jwsSigner.sign(reqOpts);
}
reqOpts.body = bodyStringifier(reqOpts.body);
this.logger.isDebugEnabled && this.logger.debug(`Executing HTTP PATCH: ${safeStringify({ reqOpts: { ...reqOpts, agent: '[REDACTED]' }})}`);
return this._request(reqOpts, responseType);
}
/**
* @function _post
* @description
* Perform a HTTP POST request.
*
* @param {string} url - The url of the resource
* @param {string} resourceType - The 'type' of resource, as defined in the Mojaloop specification
* @param {object} body - The 'body' of the POST request
* @param {string | undefined} dest - The destination participant. Leave empty if participant is unknown (e.g. `GET /parties`)
* @param {*} headers - Optional additional headers
* @param {*} query - Optional query parameters
* @param {*} responseType - Optional, defaults to `Mojaloop`
* @param {Object} transformParams
*/
async _post(url, resourceType, body, dest, headers = {}, query = {},
responseType = ResponseType.Mojaloop, transformParams = {}) {
const reqOpts = {
method: 'POST',
uri: buildUrl(this._pickPeerEndpoint(resourceType), url),
headers: {
...this._buildHeaders('POST', resourceType, dest),
...headers,
},
body: body,
qs: query,
agent: this.agent,
};
// transform the request. This will only change the request if translation is required i.e. if this.apiType is not 'fspiop'
const transformed = await this._apiTransformer.transformOutboundRequest(resourceType, reqOpts.method,
{ body: reqOpts.body, headers: reqOpts.headers, params: transformParams, $context: transformParams.$context });
reqOpts.body = transformed.body;
reqOpts.headers = { ...reqOpts.headers, ...transformed.headers };
if (responseType === ResponseType.Stream) {
reqOpts.responseType = request.responseType.Stream;
}
if ((responseType === ResponseType.Mojaloop) && this.jwsSign) {
this.jwsSigner.sign(reqOpts);
}
reqOpts.body = bodyStringifier(reqOpts.body);
this.logger.isDebugEnabled && this.logger.debug(`Executing HTTP POST: ${safeStringify({ reqOpts: { ...reqOpts, agent: '[REDACTED]' }})}`);
return this._request(reqOpts, responseType);
}
/**
* @function _buildHeaders
* @description
* Utility function for building outgoing request headers as required by the mojaloop api spec
* @param {'GET' | 'POST' | 'PUT'} method The HTTP Method
* @param {string} resourceType - The 'type' of resource, as defined in the Mojaloop specification
* @param {string | undefined} dest - The destination participant. Leave empty if participant is unknown (e.g. `GET /parties`)
*
* @returns {*} headers object for use in requests to mojaloop api endpoints
*/
_buildHeaders(method, resourceType, dest) {
const apiType = defineApiType(resourceType, this.apiType);
const isoPart = apiType === ApiType.ISO20022
? `.${ISO_20022_HEADER_PART}`
: '';
let headers = {
'content-type': `application/vnd.interoperability${isoPart}.${resourceType}+json;version=${this.resourceVersions[resourceType].contentVersion}`,
'date': new Date().toUTCString(),
};
if (this.dfspId) {
headers['fspiop-source'] = this.dfspId;
}
if(dest) {
headers['fspiop-destination'] = dest;
}
//Need to populate Bearer Token if we are in OAuth2.0 environment
if (this.wso2.auth) {
const token = this.wso2.auth.getToken();
if(token) {
headers['Authorization'] = `Bearer ${token}`;
}
}
// dont add accept header to PUT requests
if(method.toUpperCase() !== 'PUT') {
// if we are sending ISO we should "accept" it also
headers['accept'] = `application/vnd.interoperability${isoPart}.${resourceType}+json;version=${this.resourceVersions[resourceType].acceptVersion}`;
}
return headers;
}
/**
* @function _pickPeerEndpoint
* @description Utility function for picking up the right endpoint based on the resourceType
* @param {string} resourceType - The 'type' of resource, as defined in the Mojaloop specification
* @returns {string} The endpoint fot the given `resourceType`. If an endpoint can't be found, defaults to the peerEndpoint
*/
_pickPeerEndpoint(resourceType) {
return this.resourceEndpoints[resourceType] || this.peerEndpoint;
}
}
module.exports = BaseRequests;