Function: Advanced REPLACE Operation

    March 23, 2025
    + 12

    Perform the Advanced REPLACE operation where Eventing interacts with the Data Service.

    The advancedReplaceOp function:

    • Performs the Advanced REPLACE operation

    • Requires Eventing Storage (or a metadata collection) and a source collection

    • Requires a binding of type bucket alias

    • Operates on any mutation where doc.type === "control_adv_replace"

    • Always tries to insert the test document and ignores insert errors

    • Has 3 modes of operation: no_cas, bad_cas, and good_cas

    For more information about the Advanced Self-Recursion Parameter, see Advanced REPLACE Operation.

    javascript
    // Configure the settings for the advancedReplaceOp function as follows: // // Version 7.1+ // "Function Scope" // *.* (or try bulk.data if non-privileged) // Version 7.0+ // "Listen to Location" // bulk.data.source // "Eventing Storage" // rr100.eventing.metadata // Binding(s) // 1. "binding type", "alias name...", "bucket.scope.collection", "Access" // "bucket alias", "src_col", "bulk.data.source", "read and write" // // Version 6.6.1 // "Source Bucket" // source // "MetaData Bucket" // metadata // Binding(s) // 1. "binding type", "alias name...", "bucket", "Access" // "bucket alias", "src_col", "source", "read and write" function OnUpdate(doc, meta) { if (!meta.id.startsWith("control_adv_replace")) return; log('input meta', meta); log('input doc ', doc); // Setup, make sure there is a doc to "replace", ignore any errors couchbase.insert(src_col,{"id":"test_adv_replace:" + doc.ins_id},{"a:": 1}); var new_meta; if (doc.mode && doc.mode === "no_cas") { // No CAS is passed - it always succeeds new_meta = {"id":"test_adv_replace:" + doc.ins_id}; // (Optional) Set an expiry 60 seconds in the future // new_meta.expiry_date = new Date(Date.now() + 60 * 1000); } if (doc.mode && doc.mode === "bad_cas") { // Pass a non-matching CAS - it always fails new_meta = {"id":"test_adv_replace:" + doc.ins_id, "cas":"1111111111111111111"}; } if (doc.mode && doc.mode === "good_cas") { // Pass the matching or current CAS - it succeeds var tmp_r = couchbase.get(src_col,{"id":"test_adv_replace:" + doc.ins_id}); if (tmp_r.success) { // Use the current CAS to read via couchbase.get(...) new_meta = {"id":"test_adv_replace:" + doc.ins_id, "cas": tmp_r.meta.cas}; } else { log('Cannot replace due to no such key',"test_adv_replace:" + doc.ins_id); return; } } var new_doc = {id: doc.ins_id, type: "test_adv_replace", random: Math.random()}; var result = couchbase.replace(src_col,new_meta,new_doc); if (result.success) { log('success adv. replace: result',result); } else { log('failure adv. replace: id',new_meta.id,'result',result); } }