In this tutorial I will show you how to return all historical versions of an asset in Hyperledger Fabric 1.4 using the JS API. To do this, we will be using the getHistoryForKey() function. This tutorial will be based off of this example.
getHistoryForKey() takes in a key as the only argument. Example:
Now, if we attempt to execute this, we will receive a JSON parsing error. Why is this? Because we need to iterate over the results in the smart contract.
To avoid this error, we will add in a function to iterate over the past asset versions:
Now we will call this function inside of our return all versions smart contract:
And that's it! We can now get the current and all previous versions of our asset.
getHistoryForKey() takes in a key as the only argument. Example:
Code:
async returnnAllVersions(stub, args) {
const history = await stub.getHistoryForKey('0001');
return history;
}
Now, if we attempt to execute this, we will receive a JSON parsing error. Why is this? Because we need to iterate over the results in the smart contract.
To avoid this error, we will add in a function to iterate over the past asset versions:
Code:
async function getAllResults(iterator, getKeys) {
const allResults = [];
while (true) {
const res = await iterator.next();
// Check for the case where *no* results are returned.
if (!res.value && res.done) {
console.log('no value and done (no results returned)');
await iterator.close();
return allResults;
} else if (!res.value) {
throw new Error('no value and not done (internal error?)');
}
const theVal = (getKeys) ? res.value.key : res.value.value.toString('utf8');
allResults.push(theVal);
console.log(theVal);
if (res.done) {
console.log('end of data');
await iterator.close();
return allResults;
}
}
}
Now we will call this function inside of our return all versions smart contract:
Code:
async returnAllVersions(stub, args) {
const iterator = await stub.getHistoryForKey('0001');
const data = getAllResults(iterator);
return JSON.stringify(data);
}
And that's it! We can now get the current and all previous versions of our asset.