Search code examples
hyperledger-composer

Modifying an array property of a resource (participant) during a transaction


I want to modify a property of a participant which is an array of relationships during a transaction.

Let's assume I have a user that holds an array of keys like so:

participant User identified by userId {
    o String userId
    --> Key[] keys
}

asset Key identified by keyId {
    o String keyId
}

transaction modifyUserKeys {
    --> User user
}

Then in the transaction processor function I modify the array (as in adding and removing elements in it) and update the participant:

function modifyUserKeys(tx) {
    let user = tx.user;

    // create a new key via factory 
    var newKey = ...

    user.keys.push(newKey);

    return getParticipantRegistry('com.sample.User')
    .then(function (participantRegistry) {
        return participantRegistry.update(user);
    });
}

In the documentation I saw a method called addArrayValue() which adds an element to an array. Now I'm unsure whether I'm meant to use this over conventional array manipulation like in my example.

What purpose does this addArrayValue() method have and am I able to e.g. remove elements from keys via keys.pop() or is it restricted to just the addition of new elements like the documentation suggests?


Solution

  • you can use conventional (push/pop) if you like (and as you've done on the array), but newKey would need to use newRelationship()

    a useful example similar to what you're trying to achieve is here -> https://github.com/hyperledger/composer-sample-networks/blob/master/packages/fund-clearing-network/lib/clearing.js#L151 in Composer sample networks - addArrayValue() is also validating that it does not violate the model