forked from olegabu/fabric-starter-rest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.js
645 lines (579 loc) · 24.9 KB
/
api.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
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
module.exports = function(app, server) {
const fs = require("fs");
const path = require('path');
const os = require('os');
const logger = require('log4js').getLogger('api');
const jsonwebtoken = require('jsonwebtoken');
const jwt = require('express-jwt');
const _ = require('lodash');
const cfg = require('./config.js');
const UtilityService = require('./utility-service');
// upload for chaincode and app installation
const uploadDir = os.tmpdir() || './upload';
const multer = require('multer');
const upload = multer({dest: uploadDir});
const fileUpload = upload.fields([ {name: 'file', maxCount: 1}, { name: 'channelId', maxCount: 1},
{name: 'targets'}, {name: 'version', maxCount: 1}, {name: 'language', maxCount: 1},{name: 'fcn', maxCount: 1},
{name: 'args', maxCount: 1},{name: 'chaincodeType', maxCount: 1},{name: 'chaincodeId', maxCount: 1},
{name: 'chaincodeVersion', maxCount: 1},{name: 'waitForTransactionEvent', maxCount: 1},{name: 'policy', maxCount: 1}]);
// fabric client
const FabricStarterClient = require('./fabric-starter-client');
const fabricStarterClient = new FabricStarterClient();
const webAppManager = require('./web-app-manager');
// socket.io server to pass blocks to webapps
const Socket = require('./rest-socket-server');
const socket = new Socket(fabricStarterClient);
socket.startSocketServer(server, cfg.UI_LISTEN_BLOCK_OPTS).then(() => {
logger.info('started socket server');
});
// parse json payload and urlencoded params
const bodyParser = require("body-parser");
app.use(bodyParser.json({limit: '100MB', type: 'application/json'}));
app.use(bodyParser.urlencoded({extended: true, limit: '100MB'}));
// allow CORS from all urls
const cors = require('cors');
app.use(cors());
app.options('*', cors());
// serve admin and custom web apps as static
const express = require("express");
const webappDir = process.env.WEBAPP_DIR || './webapp';
app.use('/webapp', express.static(webappDir));
logger.info(`serving webapp at /webapp from ${webappDir}`);
app.use('/admin', express.static(cfg.WEBADMIN_DIR));
logger.info(`serving admin at /admin from ${cfg.WEBADMIN_DIR}`);
// serve msp directory with certificates as static
const mspDir = process.env.MSP_DIR || './msp';
const serveIndex = require('serve-index');
//TODO serveIndex should show directory listing to find certs but not working
app.use('/msp', express.static(mspDir), serveIndex('/msp', {'icons': true}));
logger.info('serving certificates at /msp from ' + mspDir);
// serve favicon
const favicon = require('serve-favicon');
if(fs.existsSync(path.join(webappDir, 'favicon.ico'))) {
app.use(favicon(path.join(webappDir, 'favicon.ico')));
}
// catch promise rejections and return 500 errors
const asyncMiddleware = fn =>
(req, res, next) => {
// logger.debug('asyncMiddleware');
Promise.resolve(fn(req, res, next))
.catch(e => {
logger.error('asyncMiddleware', e);
res.status((e && e.status) || 500).json(e && e.message);
next();
});
};
// require presence of JWT in Authorization Bearer header
const jwtSecret = fabricStarterClient.getSecret();
app.use(jwt({secret: jwtSecret}).unless({path: ['/', '/users', '/domain', '/mspid', '/config', new RegExp('/api-docs'), '/api-docs.json', /\/webapp/, /\/webapps\/.*/, '/admin/', '/msp/']}));
// use fabricStarterClient for every logged in user
const mapFabricStarterClient = {};
app.use(async(req, res, next) => {
if(req.user) {
const login = req.user.sub;
let client = mapFabricStarterClient[login];
if(client) {
logger.debug('cached client for', login);
req.fabricStarterClient = client;
} else {
logger.debug('new client for', login); //TODO: should not be reachable
req.fabricStarterClient = new FabricStarterClient();
await req.fabricStarterClient.init();
try {
await req.fabricStarterClient.loginOrRegister(login);
} catch(e) {
logger.error('loginOrRegister', e);
res.status(500).json(e && e.message);
}
mapFabricStarterClient[login] = req.fabricStarterClient;
}
}
next();
});
app.get('/', (req, res) => {
res.status(200).send('Welcome to fabric-starter REST server');
});
app.post('/cert', (req, res) => {
res.json(fabricStarterClient.decodeCert(req.body.cert));
});
/**
* Show network name (as defined by DOMAIN env variable at setup time)
* @route GET /domain
* @group config - Queries for config
* @returns {string} 200 - DOMAIN
* @returns {Error} default - Unexpected error
*/
app.get('/domain', (req, res) => {
res.json(cfg.domain);
});
/**
* Show name (MSPID) of my organization
* @route GET /mspid
* @group config - Queries for config
* @returns {string} 200 - MSPID
* @returns {Error} default - Unexpected error
*/
app.get('/mspid', (req, res) => {
res.json(fabricStarterClient.getMspid());
});
//TODO use for development only as it may expose sensitive data
/**
* Network config json to aid debugging; use for development only as it may expose sensitive data
* @route GET /config
* @group config - Queries for config
* @returns {object} 200 - Network config
* @returns {Error} default - Unexpected error
*/
app.get('/config', (req, res) => {
res.json(fabricStarterClient.getNetworkConfig());
});
/**
* Query chaincodes installed on the first peer of my organization
* @route GET /chaincodes
* @group chaincodes - Queries and operations on chaincode
* @returns {object} 200 - Array of chaincode objects
* @returns {Error} default - Unexpected error
* @security JWT
*/
app.get('/chaincodes', asyncMiddleware(async(req, res, next) => {
res.json(await req.fabricStarterClient.queryInstalledChaincodes());
}));
/**
* Install chaincode
* @route POST /chaincodes
* @group chaincodes - Queries and operations on chaincode
* @param {string} channelId.formData.required - channel - eg: common
* @param {file} file.formData.required - chaincode source code archived in zip - eg: chaincode_example02.zip
* @param {string} targets.formData.required - list of peers to install to - eg: ["peer0.org1.example.com:7051"]
* @param {string} version.formData (default 1.0) - chaincode version - eg: 1.0
* @param {string} language.formData (default node) - chaincode language - eg: golang
* @returns {object} 200 - Chaincode installed
* @returns {Error} default - Unexpected error
* @security JWT
* @consumes multipart/form-data
*/
app.post('/chaincodes', fileUpload, asyncMiddleware(async(req, res, next) => {
res.json(await req.fabricStarterClient.installChaincode(
req.files['file'][0].originalname.substring(0, req.files['file'][0].originalname.length - 4),
req.files['file'][0].path, req.body.version, req.body.language, uploadDir));
}));
/**
* @typedef User
* @property {string} username.required - username - eg: oleg
* @property {string} password.required - password - eg: pass
*/
/**
* Login or register user.
* @route POST /users
* @group users - Authentication and operations about users
* @param {User.model} user.body.required
* @returns {object} 200 - User logged in and his JWT returned
* @returns {Error} default - Unexpected error
*/
app.post('/users', asyncMiddleware(async(req, res, next) => {
if(!mapFabricStarterClient[req.body.username]) {
mapFabricStarterClient[req.body.username] = new FabricStarterClient();
}
req.fabricStarterClient = mapFabricStarterClient[req.body.username];
await req.fabricStarterClient.init();
await req.fabricStarterClient.loginOrRegister(req.body.username, req.body.password || req.body.username);
const token = jsonwebtoken.sign({sub: req.fabricStarterClient.user.getName()}, jwtSecret);
logger.debug('token', token);
res.json(token);
}));
/**
* Query channels joined by the first peer of my organization
* @route GET /channels
* @group channels - Queries and operations on channels
* @returns {object} 200 - Array of channel objects
* @returns {Error} default - Unexpected error
* @security JWT
*/
app.get('/channels', asyncMiddleware(async(req, res, next) => {
res.json(await req.fabricStarterClient.queryChannels());
}));
/**
* @typedef Channel
* @property {string} channelId.required - channel name - eg: common
*/
/**
* Join channel
* @route POST /channels/{channelId}
* @group channels - Queries and operations on channels
* @param {string} channelId.path.required - channel - eg: common
* @returns {object} 200 - Channel joined
* @returns {Error} default - Unexpected error
* @security JWT
*/
app.post('/channels/:channelId', asyncMiddleware(async(req, res, next) => {
let ret = await joinChannel(req.params.channelId, req.fabricStarterClient);
res.json(ret);
}));
/**
* Create channel and join it
* @route POST /channels
* @group channels - Queries and operations on channels
* @param {Channel.model} channel.body.required
* @returns {object} 200 - Channel created
* @returns {Error} default - Unexpected error
* @security JWT
*/
app.post('/channels', asyncMiddleware(async(req, res, next) => {
await req.fabricStarterClient.createChannel(req.body.channelId);
res.json(await joinChannel(req.body.channelId, req.fabricStarterClient));
}));
async function joinChannel(channelId, fabricStarterClient) {
try {
const ret = await fabricStarterClient.joinChannel(channelId);
UtilityService.retryOperation(cfg.LISTENER_RETRY_COUNT, async function() {
await socket.registerChannelChainblockListener(channelId);
});
return ret;
} catch(error) {
logger.error(error.message);
throw new Error(error.message);
}
}
/**
* Query channel info
* @route GET /channels/{channelId}
* @group channels - Queries and operations on channels
* @param {string} channelId.path.required - channel - eg: common
* @returns {object} 200 - Channel block info
* @returns {Error} default - Unexpected error
* @security JWT
*/
app.get('/channels/:channelId', asyncMiddleware(async(req, res, next) => {
res.json(await req.fabricStarterClient.queryInfo(req.params.channelId));
}));
/**
* Query organizations in a channel
* @route GET /channels/{channelId}/orgs
* @group channels - Queries and operations on channels
* @param {string} channelId.path.required - channel - eg: common
* @param {boolean} filter.path.required - reject orderer name flag
* @returns {object} 200 - Array of organization objects with names (MSPIDs)
* @returns {Error} default - Unexpected error
* @security JWT
*/
app.get('/channels/:channelId/orgs', asyncMiddleware(async(req, res, next) => {
res.json(await req.fabricStarterClient.getOrganizations(req.params.channelId, req.query.filter));
}));
/**
* Query peers that joined a channel
* @route GET /channels/{channelId}/peers
* @group channels - Queries and operations on channels
* @param {string} channelId.path.required - channel - eg: common
* @returns {object} 200 - Array of peer names
* @returns {Error} default - Unexpected error
* @security JWT
*/
app.get('/channels/:channelId/peers', asyncMiddleware(async(req, res, next) => {
res.json(await req.fabricStarterClient.getPeersForOrgOnChannel(req.params.channelId));
}));
/**
* Query peers of an organization
* @route GET /orgs/{org}/peers
* @group orgs - Queries for organizations
* @param {string} org.path.required - organization - eg: org1
* @returns {object} 200 - Array of peer objects
* @returns {Error} default - Unexpected error
* @security JWT
*/
app.get('/orgs/:org/peers', asyncMiddleware(async(req, res, next) => {
res.json(await req.fabricStarterClient.getPeersForOrg(req.params.org || cfg.org));
}));
/**
* @typedef Organization
* @property {string} orgId.required - organization name by convention same as MSPID- eg: org1
*/
/**
* Add organization to a channel
* @route POST /channels/{channelId}/orgs
* @group channels - Queries and operations on channels
* @param {string} channelId.path.required - channel - eg: common
* @param {Organization.model} organization.body.required
* @returns {object} 200 - Organization added
* @returns {Error} default - Unexpected error
* @security JWT
*/
app.post('/channels/:channelId/orgs', asyncMiddleware(async(req, res, next) => {
res.json(await req.fabricStarterClient.addOrgToChannel(req.params.channelId, req.body.orgId, req.body.orgIp));
}));
/**
* Query a given block in a channel
* @route GET /channels/{channelId}/blocks/{number}
* @group channels - Queries and operations on channels
* @param {string} channelId.path.required - channel - eg: common
* @param {integer} number.path.required - block number - eg: 1
* @returns {object} 200 - Block
* @returns {Error} default - Unexpected error
* @security JWT
*/
app.get('/channels/:channelId/blocks/:number', asyncMiddleware(async(req, res, next) => {
res.json(await req.fabricStarterClient.queryBlock(req.params.channelId, parseInt(req.params.number)));
}));
/**
* Query a given transaction in a channel
* @route GET /channels/{channelId}/transactions/{id}
* @group channels - Queries and operations on channels
* @param {string} channelId.path.required - channel - eg: common
* @param {string} id.path.required - transaction id - eg: 5e4c57948cf6fe465...
* @returns {object} 200 - Transaction
* @returns {Error} default - Unexpected error
* @security JWT
*/
app.get('/channels/:channelId/transactions/:id', asyncMiddleware(async(req, res, next) => {
res.json(await req.fabricStarterClient.queryTransaction(req.params.channelId, req.params.id));
}));
/**
* Query chaincodes instantiated on a channel
* @route GET /channels/{channelId}/chaincodes
* @group channels - Queries and operations on channels
* @param {string} channelId.path.required - channel - eg: common
* @returns {object} 200 - Object with an array of chaincodes
* @returns {Error} default - Unexpected error
* @security JWT
*/
app.get('/channels/:channelId/chaincodes', asyncMiddleware(async(req, res, next) => {
res.json(await req.fabricStarterClient.queryInstantiatedChaincodes(req.params.channelId));
}));
/**
* @typedef Instantiate
* @property {string} chaincodeId.required - chaincode name - eg: reference
* @property {string} fcn (default fcn) - chaincode function name - eg: init
* @property {Array.<string>} args (default []) - string encoded arguments to chaincode function - eg: ["account","1","{name:\"one\"}"]
* @property {string} chaincodeVersion - chaincode version (default 1.0) - eg: 1.0
* @property {string} chaincodeType - chaincode language (default node) - eg: golang
* @property {Array.<string>} targets - list of peers to send for endorsement - eg: ["peer0.org1.example.com:7051"]
* @property {boolean} waitForTransactionEvent - respond only when transaction commits - eg: true
*/
/**
* Instantiate chaincode
* @route POST /channels/{channelId}/chaincodes
* @group channels - Queries and operations on channels
* @param {string} channelId.path.required - channel - eg: common
* @param {Instantiate.model} instantiate.body.required - instantiate request
* @returns {object} 200 - Transaction id
* @returns {Error} default - Unexpected error
* @security JWT
*/
app.post('/channels/:channelId/chaincodes', fileUpload, asyncMiddleware(async(req, res, next) => {
if(req.files && req.files['file'])
res.json(await req.fabricStarterClient.instantiateChaincode(req.params.channelId, req.body.chaincodeId,
req.body.chaincodeType, req.body.fcn, extractArgs(req.body.args), req.body.chaincodeVersion, req.body.targets, req.body.waitForTransactionEvent, req.body.policy, req.files['file'][0].path));
else
res.json(await req.fabricStarterClient.instantiateChaincode(req.params.channelId, req.body.chaincodeId,
req.body.chaincodeType, req.body.fcn, extractArgs(req.body.args), req.body.chaincodeVersion, req.body.targets, req.body.waitForTransactionEvent, req.body.policy));
}));
/**
* Upgrade chaincode
* @route POST /channels/{channelId}/chaincodes/upgrade
* @group channels - Queries and operations on channels
* @param {string} channelId.path.required - channel - eg: common
* @param {upgrade.model} upgrade.body.required - upgrade request
* @returns {object} 200 - Transaction id
* @returns {Error} default - Unexpected error
* @security JWT
*/
app.post('/channels/:channelId/chaincodes/upgrade', fileUpload, asyncMiddleware(async(req, res, next) => {
if(req.files['file'])
res.json(await req.fabricStarterClient.upgradeChaincode(req.params.channelId, req.body.chaincodeId,
req.body.chaincodeType, req.body.fcn, extractArgs(req.body.args), req.body.chaincodeVersion, req.body.targets, req.body.waitForTransactionEvent, req.body.policy, req.files['file'][0].path));
else
res.json(await req.fabricStarterClient.upgradeChaincode(req.params.channelId, req.body.chaincodeId,
req.body.chaincodeType, req.body.fcn, extractArgs(req.body.args), req.body.chaincodeVersion, req.body.targets, req.body.waitForTransactionEvent, req.body.policy));
}));
/**
* Query chaincode
* @route GET /channels/{channelId}/chaincodes/{chaincodeId}
* @group chaincode - Invoke and query chaincode
* @param {string} channelId.path.required - channel - eg: common
* @param {string} chaincodeId.path.required - channel - eg: reference
* @param {string} fcn.query.required - chaincode function name - eg: list
* @param {string} args.query.required - string encoded arguments to chaincode function - eg: ["account"]
* @param {string} targets.query - list of peers to query - eg: ["peer0.org1.example.com:7051"]
* @param {boolean} unescape.query - return not array of strings but array of json objects - eg. true
* @returns {object} 200 - An array of query results
* @returns {Error} default - Unexpected error
* @security JWT
*/
app.get('/channels/:channelId/chaincodes/:chaincodeId', asyncMiddleware(async(req, res, next) => {
let ret = await req.fabricStarterClient.query(req.params.channelId, req.params.chaincodeId,
req.query.fcn, req.query.args, extractTargets(req, "query"));
if(req.query.unescape) {
ret = ret.map(o => {
let u = o;
try {
u = JSON.parse(o);
} catch(e) {
logger.debug('cannot JSON.parse', e);
}
return u;
});
}
res.json(ret);
}));
/**
* @typedef Invoke
* @property {string} fcn.required - chaincode function name - eg: put
* @property {Array.<string>} args.required - string encoded arguments to chaincode function - eg: ["account","1","{name:\"one\"}"]
* @property {Array.<string>} targets - list of peers to send for endorsement - eg: ["peer0.org1.example.com:7051"]
* @property {boolean} waitForTransactionEvent - respond only when transaction commits - eg: true
*/
/**
* Invoke chaincode
* @route POST /channels/{channelId}/chaincodes/{chaincodeId}
* @group chaincode - Invoke and query chaincode
* @param {string} channelId.path.required - channel - eg: common
* @param {string} chaincodeId.path.required - channel - eg: reference
* @param {Invoke.model} invoke.body.required - invoke request
* @returns {object} 200 - Transaction id
* @returns {Error} default - Unexpected error
* @security JWT
*/
app.post('/channels/:channelId/chaincodes/:chaincodeId', asyncMiddleware(async(req, res, next) => {
let result = await req.fabricStarterClient.invoke(req.params.channelId, req.params.chaincodeId,
req.body.fcn, req.body.args, extractTargets(req, "body"), req.body.waitForTransactionEvent, req.body.transientMap);
res.json(result);
}));
/**
* Query member organizations of current consortium
* @route GET /consortium/members
* @group consortium - view and control participants
* @returns {object} 200 - Array of MSPIDs
* @returns {Error} default - Unexpected error
* @security JWT
*/
app.get('/consortium/members', asyncMiddleware(async(req, res, next) => {
res.json(await req.fabricStarterClient.getConsortiumMemberList());
}));
/**
* Add organization to the consortium
* @route POST /consortium/members
* @group consortium - view and control participants
* @param {Organization.model} organization.body.required
* @returns {object} 200 - Organization added
* @returns {Error} default - Unexpected error
* @security JWT
*/
app.post('/consortium/members', asyncMiddleware(async(req, res, next) => {
console.log(req.fabricStarterClient);
res.json(await req.fabricStarterClient.addOrgToConsortium(req.body.orgId));
}));
/**
* Get list of deployed custom web applications
* @route GET /applications
* @group applications - Web applications
* @returns {Error} default - Unexpected error
* @security JWT
*/
app.get('/applications', fileUpload, asyncMiddleware(async(req, res, next) => {
res.json(await webAppManager.getWebAppsList());
}));
/**
* Deploy new web application
* @route POST /applications
* @group applications - Web applications
* @param {file} file.formData.required - application compiled folder archived in zip - eg: coolwebapp.zip
* @returns {Error} default - Unexpected error
* @security JWT
*/
app.post('/applications', fileUpload, asyncMiddleware(async (req, res, next) => {
let fileUploadObj = _.get(req, "files.file[0]");
const fileBaseName = path.basename(fileUploadObj.originalname, path.extname(fileUploadObj.originalname));
res.json(await webAppManager.provisionWebAppFromPackage(fileUploadObj)
.then(extractParentPath => {
let appFolder=path.resolve(extractParentPath, fileBaseName);
webAppManager.redeployWebapp(app, fileBaseName, appFolder);
return webAppManager.getWebAppsList();
}));
}));
/**
* Get list of deployed custom middlewares
* @route GET /middlewares
* @group middlewares - Middlewares
* @returns {Error} default - Unexpected error
* @security JWT
*/
app.get('/middlewares', fileUpload, asyncMiddleware(async(req, res, next) => {
const list = await webAppManager.getMiddlewareList();
res.json(list);
}));
/**
* Deploy new middleware
* @route POST /middlewares
* @group middlewares - Web applications
* @param {file} file.formData.required - middlewares's js file
* @returns {Error} default - Unexpected error
* @security JWT
*/
app.post('/middlewares', fileUpload, asyncMiddleware(async (req, res, next) => {
let fileUploadObj = _.get(req, "files.file[0]");
res.json(await webAppManager.provisionMiddleware(fileUploadObj)
.then(extractParentPath => {
const route = require(extractParentPath);
route(app, asyncMiddleware);
return webAppManager.getMiddlewareList();
}));
}));
function extractArgs(args){
let checkedArgs;
if (args && _.isString(args))
checkedArgs = JSON.parse(args);
else if (args && _.isArray(args))
checkedArgs = args;
return checkedArgs;
}
function extractTargets(req, prop) {
const result = {};
let targets = _.get(req, `${prop}.targets`);
try {
targets = JSON.parse(targets);
} catch(e) {
logger.warn("Targets are not parseable", targets, e.message);
}
if(targets) result.targets = targets;
if(!targets) {
let peers = _.concat([], _.get(req, `${prop}.peer`) || _.get(req, `${prop}.peers`) || []);
if(!_.isEmpty(peers)) {
result.peers = _.map(peers, p => {
const parts = _.split(p, "/"); //format: org/peer0
const peerOrg = parts[0];
const peerName = parts[1];
return `${peerName}.${peerOrg}.${cfg.domain}:7051`;
})
}
}
return result;
}
const expressSwagger = require('express-swagger-generator')(app);
// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#swagger-object
expressSwagger({
swaggerDefinition: {
info: {
description: 'API server for Hyperledger Fabric',
title: 'fabric-starter-rest',
version: `FABRIC_STARTER_REST_VERSION=${process.env.FABRIC_STARTER_REST_VERSION || 'latest'}`,
},
// host: 'localhost:4000',
// basePath: '/v1',
basePath: '/',
produces: [
"application/json",
// "application/xml"
],
schemes: ['http'/*, 'https'*/],
securityDefinitions: {
JWT: {
type: 'apiKey',
in: 'header',
name: 'Authorization',
description: "Paste the jwt you received from logging in by a post to /users ex.: Bearer eyJhbGci...",
}
}
},
basedir: __dirname, //app absolute path
files: ['./api.js'] //Path to the API handle folder
});
};