javascriptcloudkitcloudkit-web-services

Updating a record with CloudKit JS


CloudKit JS offers methods to save, delete and fetch records but there is no easy methods to update en existing one. The documentation explains how to do it:

var query = {
    operationType : 'forceUpdate',
    recordType: 'List',
    record : {
        recordName : 'TheRecordIWannaUpdate',
        fields: { TheFieldToUpdate: { 'value': 42}}
    }
};
container.publicCloudDatabase.performQuery(query).then(function(response) {
    if(response.hasErrors) {
        console.log(response.errors[0]);
    } else {
        console.log('It's working')
    }
});

I tried this code and it returns It's workinghowever my record is not updated, what is wrong with this code?


Solution

  • To update a record you can use the recordChangeTag. The latest recordChangeTag is needed.

    Documentation

    When you fetch a record from the server, you get the current version of that record as it exists on the server. However, at any time after you fetch a record, other users might save a newer version of the record to the server. Every time a record is saved, the server updates the record’s change token to a new value. When you save your instance of the record to the server, the server compares the token in your record with the token on the server. If the two tokens match, the server knows that you modified the latest version of the record and that your changes can be applied right away. If the two tokens do not match, the server applies the save policy your app specified to determine how to proceed.

    Example

    var record = {
        recordType: 'List',
        recordName: TheRecordIWannaUpdate,
        recordChangeTag: TheRecordTag,
        fields: {
          TheFieldToUpdate: {
            value: 42
          }
        }
    };
    

    The Save Policy does not work for me, but you can add it.

    var options = {  
          zoneName: undefined,
          operationType : 'forceUpdate'
      };
    
    container.publicCloudDatabase.saveRecord(record,options)
        .then(function(response) {
        if(response.hasErrors) {
            console.log(response.errors[0]);
        } else {
            console.log("It's working");
        }
     });