/** Referenced from: https://github.com/ksachdeva/hyperledger-fabric-example/blob/c41fcaa352e78cbf3c7cfb210338ac0f20b8357e/src/client.ts */ import * as fs from 'fs' ; import { join } from 'path' ; import Client from 'fabric-client' ; import { IEnrollmentRequest , IRegisterRequest } from 'fabric-ca-client' ; import { identity } from '../utils/identity' ; export type UserParams = IRegisterRequest ; export type AdminParams = IEnrollmentRequest ; const l = console . log ; export namespace SelfGenContext { interface IdentityFiles { privateKey : string ; signedCert : string ; } export async function getClient ( ) { const keyStore = identity ( ) . keyStore ; const user = identity ( ) . user ; const org = identity ( ) . org ; const contextPath = join ( keyStore + '/' + user ) ; fs . readFile ( contextPath , 'utf8' , async function ( err , data ) { if ( err ) { const client = new Client ( ) ; l ( 'Setting up the cryptoSuite ..' ) ; const cryptoSuite = Client . newCryptoSuite ( ) ; cryptoSuite . setCryptoKeyStore ( Client . newCryptoKeyStore ( { path : keyStore } ) ) ; client . setCryptoSuite ( cryptoSuite ) ; l ( 'Setting up the keyvalue store ..' ) ; const store = await Client . newDefaultKeyValueStore ( { path : keyStore } ) ; client . setStateStore ( store ) ; l ( 'Creating the admin user context ..' ) ; const privateKeyFile = fs . readdirSync ( keyStore + '/keystore' ) [ 0 ] ; const cryptoContentOrgAdmin = { privateKey : keyStore + '/keystore/' + privateKeyFile , signedCert : keyStore + '/signcerts/cert.pem' } ; await client . createUser ( { username : user , mspid : `${ org }MSP` , cryptoContent : cryptoContentOrgAdmin , skipPersistence : false } ) ; return client ; } else { l ( `Context exists in ${ contextPath }` ) ; } } ) ; } }