Function: Basic Binary KV
Goal: Show Basic Bucket Op Binary Write and Read.
-
This function basicBinaryKV demonstrates creating, marshalling and unmarshalling binary docs.
-
Requires a metadata bucket and a source bucket aliased to "src_bkt" in mode read+write.
-
Will operate on any mutation where the KEY or meta.id starts with "basicbinarykv".
-
The function will create one binary document and write it then read it back.
-
The document written will be read back and verified demonstrating binary marshalling and unmarshalling.
-
On a second deployment the binary doc that was written on the first deployment will cause a mutation.
// Deploy UnDeploy and re-Deploy a second time to excercise this function.
function OnUpdate(doc, meta) {
if (meta.id === "bindoc_kvput") {
// if we deploy/undeploy/deploy we will see the document we created on the first deploy
// Note that meta.datatype === "binary" on this mutation.
log ("4. received binary mutation",doc,"unmarshalled ("+new Uint8Array(doc)+") meta:",meta);
log ("5. deleting the binary doc with KEY 'bindoc_kvput'");
delete src_bkt["bindoc_kvput"];
return;
}
if (!meta.id.startsWith("basicbinarykv") || src_bkt["bindoc_kvput"]) return;
var arr = new Uint8Array([1, 0, 2, 3]);
var bindoc = arr.buffer;
// Write via a Basic Bucket Op, i.e. JavaScript map exposed via a bucket binding.
// Note the JavaScript map only returns the doc (unlike the mutations received via
// OnUpate which also has meta) so do not know if we just read a binary doc or text
src_bkt["bindoc_kvput"] = bindoc;
log ("1. wrote bindoc",bindoc,"unmarshalled ("+new Uint8Array(bindoc)+")");
// Read via a Basic Bucket Op, i.e. JavaScript map exposed via a bucket binding
var retdoc = src_bkt["bindoc_kvput"];
log ("2. read retdoc",retdoc)
log ("3. test bindoc("+
new Uint8Array(bindoc)+") == retdoc("+
new Uint8Array(retdoc)+") => " + buffersEqual(bindoc,retdoc));
}
function buffersEqual(buf1, buf2) {
if (buf1.byteLength != buf2.byteLength) return false;
var dv1 = new Uint8Array(buf1);
var dv2 = new Uint8Array(buf2);
for (var i = 0; i != buf1.byteLength; i++) {
if (dv1[i] != dv2[i]) return false;
}
return true;
}
INPUT: KEY basicbinarykv:1
{
"id": 1,
"type": "basicbinarykv"
}
FIRST DEPLOYMENT
2021-04-10T15:13:14.903-07:00 [INFO] "1. wrote bindoc" {} "unmarshalled (1,0,2,3)"
2021-04-10T15:13:14.904-07:00 [INFO] "2. read retdoc" {}
2021-04-10T15:13:14.904-07:00 [INFO] "3. test bindoc(1,0,2,3) == retdoc(1,0,2,3) => true"
SECOND DEPLOYMENT (note the "datatype" of "binary")
2021-04-10T15:14:06.581-07:00 [INFO] "4. received binary mutation" {} "unmarshalled (1,0,2,3) meta:"
{"cas":"1618092795477098496","id":"bindoc_kvput","expiration":0,"flags":0,"vb":430,"seq":9,"datatype":"binary"}
2021-04-10T15:14:06.581-07:00 [INFO] "5. deleting the binary with KEY 'bindoc_kvput'"