Reputation: 51
I am trying to create a simple hyperledger chaincode in composer that takes a loan number and if it exists, updates the asset associated else creates a new asset.
My model file looks like this:
asset Loan identified by loanNum{
o String loanNum
o Double balance
}
transaction createTransaction {
o String loanNum
o Double transAmount
}
My script looks like this:
function createTransaction(tx) {
var NS = 'org.acme.ra';
var factory = getFactory();
var loanToUpdate
//returns all assets
return getAssetRegistry(NS + '.Loan')
.then(function(assetRegistry){
return assetRegistry.exists(tx.loanNum);
})
.then(function(exists){
if (exists) {
return getAssetRegistry(NS + '.Loan')
.then(function(assetRegistry2){
loanToUpdate = assetRegistry2.get(tx.loanNum)
loanToUpdate.balance = tx.transAmount;
return assetRegistry2
})
.then(function(updateAssetRegistry){
return updateAssetRegistry.update(loanToUpdate)//broken right here
})
}
else {
return getAssetRegistry(NS + '.Loan')
.then(function(assetRegistry2){
var newLoan =factory.newResource(NS,'Loan',tx.loanNum);
newLoan.balance = tx.transAmount;
return assetRegistry2.add(newLoan);
})
}
})
}
Script Summary:
When bool is False the script works correctly and creates a new asset, but when bool is True and the transaction contains loan number that already exists I get the error "Error: Expected a Resource or Concept."
EDIT
Now that i am getting more experience with this, i think it can be done much easier with built in relationships but ill post my updated functional code below.
Updated Code with Fix:
function createTransaction(tx) {
var NS = 'org.acme.ra';
var factory = getFactory();
var loanToUpdate
//returns all assets
return getAssetRegistry(NS + '.Loan')
.then(function(assetRegistry){
return assetRegistry.exists(tx.loanNum);
})
.then(function(exists){
if (exists) {
return getAssetRegistry(NS + '.Loan')
.then(function(assetRegistry2){
return assetRegistry2.get(tx.loanNum);
})
.then(function(updateloan){
loanToUpdate = updateloan
loanToUpdate.balance = tx.transAmount;
return getAssetRegistry(NS + '.Loan')
})
.then(function(assetRegistry3){
return assetRegistry3.update(loanToUpdate);
})
}
else {
return getAssetRegistry(NS + '.Loan')
.then(function(assetRegistry2){
var newLoan = factory.newResource(NS,'Loan',tx.loanNum);
newLoan.balance = tx.transAmount;
return assetRegistry2.add(newLoan);
})
}
})
}
Upvotes: 2
Views: 2239
Reputation: 5868
get on an asset registry returns a promise, so the line
loanToUpdate = assetRegistry2.get(tx.loanNum)
needs to be part of the promise chain and so you need a .then
block to process the returned value before you can update it.
Upvotes: 3