1+ /*
2+ * SPDX-License-Identifier: Apache-2.0
3+ */
4+
5+ 'use strict' ;
6+
7+ const { Gateway, Wallets } = require ( 'fabric-network' ) ;
8+ const fs = require ( 'fs' ) ;
9+ const path = require ( 'path' ) ;
10+
11+ const WALLET_PATH = path . join ( __dirname , '..' , '..' , '..' , '..' , '..' , 'wallet' ) ;
12+ const CCP_PATH = path . resolve ( __dirname , '..' , '..' , '..' , '..' , '..' , 'network' , 'organizations' , 'peerOrganizations' , 'org1.example.com' , 'connection-org1.json' ) ;
13+
14+ async function getContractAndGateway ( { username, chaincode, contract} ) {
15+ // load the network configuration
16+ const ccp = JSON . parse ( fs . readFileSync ( CCP_PATH , 'utf8' ) ) ;
17+
18+ // Create a new file system based wallet for managing identities.
19+ const wallet = await Wallets . newFileSystemWallet ( WALLET_PATH ) ;
20+
21+ // Check to see if we've already enrolled the user.
22+ const identity = await wallet . get ( username ) ;
23+ if ( ! identity ) throw new Error ( `An identity for the user "${ username } " does not exist in the wallet` ) ;
24+
25+ // Create a new gateway for connecting to our peer node.
26+ const gateway = new Gateway ( ) ;
27+ await gateway . connect ( ccp , { identity, discovery : { enabled : true , asLocalhost : true } } ) ;
28+
29+ // Get the network (channel) our contract is deployed to.
30+ const network = await gateway . getNetwork ( 'mychannel' ) ;
31+
32+ // Get the contract from the network.
33+ return { contract : network . getContract ( chaincode , contract ) , gateway} ;
34+ }
35+
36+
37+ module . exports = {
38+ getContractAndGateway
39+ }
0 commit comments