Bhuwan Adhikari
Bhuwan Adhikari

Reputation: 1009

History of asset in Hyperledger Fabric

I am using node.js to write chaincode and I want to get the history of drug in pharmaceutical supply chain. I deployed chaincode, invoked manufacture and buy contract which modifies the drug's current state from one owner to another owner. Infact, I just modified commercial paper chaincode for this. The change in owner is reflected in couchdb database. But when I try to get the history of drug by drug key it doesn't work as expected.

Code I used


const promiseOfIterator = this.ctx.stub.getHistoryForKey(drugKey);
const results = [];
for await (const keyMod of promiseOfIterator) {
            
            const resp = {
                timestamp: keyMod.timestamp,
                txid: keyMod.tx_id
            }
            if (keyMod.is_delete) {
                resp.data = 'KEY DELETED';
            } else {
                resp.data = keyMod.value.toString('utf8');
            }
            results.push(resp);
        }
return results;

When I printed the results, it gives: [] And when I do this: Drug.fromBuffer(getDrugHistoryResponse); and print it, it gives Drug { class: 'org.medicochainnet.drug', key: ':', currentState: null }

How to make this work? What am I doing wrong here? Please help me.

Upvotes: 0

Views: 656

Answers (2)

Felix
Felix

Reputation: 41

I have done it in a demo like that:

const promiseOfIterator = await this.ctx.stub.getHistoryForKey(drugKey);
const results = [];
while(true){
 let res = await promiseOfIterator.next();
  //In the loop you have to check if the iterator has values or if its done 
  if(res.value){do your actions} 
  if(res.done){
   // close the iterator 
   await promiseOfIterator.close()
   // exit the loop
   return results
   }
}

Check the Mozilla Documentation for more information about Iterators in Javascript. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators

Upvotes: 0

Felix
Felix

Reputation: 41

the function

ctx.stub.getHistoryForKey(drugKey); 

is an asynchronous function. So you need to add await

const promiseOfIterator = await this.ctx.stub.getHistoryForKey(drugKey);

Then you can iterate over the result.

Upvotes: 1

Related Questions