Search code examples
javascripthyperledger-fabrichyperledger

insert data as bulk hyperledger fabric


how I can insert 5 students or more at once or as bulk, can anyone advise please?

this is my code :

async CreateStudent(ctx) {
    const args = super.parseArgs(ctx);
    const Key = super.generateKey(ctx, 10);
    const validatedArgs = super.validateSchema(studentSchema, args);
    const {
      name,
      email,
      identityNumber,
      password,
      mobile,
    } = validatedArgs;

    const output = await createStudent(
      ctx,
      Key,
      name,
      email,
      identityNumber,
      password,
      mobile,
    );
    return output;
  }

then the createStudent function is:

exports.createStudent = async (
  ctx,
  studentID,
  name,
  email,
  identityNumber,
  password,
  mobile,
) => {
  // validate submitter to belong to Org2MSP
  const clientMSPID = ctx.clientIdentity.getMSPID();
  if (clientMSPID !== "Org2MSP") {
    throw new Error(
      "AUTHENTICATION_ERROR client is not authorized to create new products"
    );
  }
  // Get ID of submitting client identity
  const organizationId = ctx.clientIdentity.getID();

  const Record = {
    organizationId,
    name,
    email,
    identityNumber,
    password,
    mobile,
    docType: "student",
  };

  const seconds = ctx.stub.getTxTimestamp().seconds.toString();
  const nanos = ctx.stub.getTxTimestamp().nanos.toString().slice(0, 3);
  Record.createdAt = +`${seconds}${nanos}`;

  await ctx.stub.putState(studentID, Buffer.from(JSON.stringify(Record), "utf8"));
  return JSON.stringify({ Key: studentID, Record });
};

when I invoke the code from the terminal, how I can insert more than one student at once?

peer chaincode invoke -o localhost:7050 --ordererTLSHostnameOverride orderer.example.com --tls --cafile ${PWD}/organizations/ordererOrganizations/example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C mychannel -n supplychain --peerAddresses localhost:7051 --tlsRootCertFiles ${PWD}/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt --peerAddresses localhost:9051 --tlsRootCertFiles ${PWD}/organizations/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt --peerAddresses localhost:11051 --tlsRootCertFiles ${PWD}/organizations/peerOrganizations/org3.example.com/peers/peer0.org3.example.com/tls/ca.crt -c '{"Args":["CreateStudent","{"name":"student","email":"test@","identityNumber":"123","password":"123","mobile":"test"}"]}'

thanks in advance


Solution

  • The code snippets below show an example of a Node.js program using an array of blockchain items and then making a call to a function which will either write each array item one call at a time or else write the array by dividing it into segments. This means that the array could be any size, but that only a predefined section is cut out for each transaction. Not all of the code is shown, just the bits to give you an idea. Using an array in the command line contract call may not be practical. Try using a Node.js program instead - it will be cleaner.

    Client Code

    const saveBatchfeedBatch = async (firstBatchId, lastBatchId, inIncrements) => {
      let counter = 0;
      //saveArray
      let batchArray = [];
      batchArray = createBatchfeedBatch(firstBatchId, lastBatchId);
      console.log(`batchArray length is ${batchArray.length}`);
      console.log(JSON.stringify(batchArray));
      return;
    
      if (inIncrements === true) {
        await network.saveArrayOneAtATime( "createAsset", batchArray);
      } else {
        await network.saveArrayInSegments( "saveArray", batchArray);
      }
    };
    
    
    Contract function  
    
    
    /**
       * This method is used to write an array of JSON objects to the blockchain.
       *
       * @param {The contract} ctx
       * @param {An array of assets} strArray
       */
      async saveArray(ctx, strArray) {
        try {
          const newBatchFeed = JSON.parse(strArray);
    
          for (let i = 0; i < newBatchFeed.length; i++) {
            await ctx.stub.putState(
              newBatchFeed[i].id,
              Buffer.from(JSON.stringify(newBatchFeed[i]))
            );
          }
        } catch (error) {
          console.log(error);
          throw error;
        }
    
      }