Reputation: 544
It appears that @google-cloud/datastore
doesn't provide a method for comparing keys, and keys themselves aren't comparable. Is there a proper way to compare keys? I've taken a few stabs myself:
function compare(key1, key2) {
return (key1.kind == key2.kind) && (key1.id == key2.id)
}
However, this doesn't work for keys with ancestors or keys with only kinds. So something more general might look like
function compare(key1, key2) {
if (key1.path.length != key2.path.length) {
return false;
}
for (var i = 0; i < key1.path.length; i++) {
if (key1.path[i] != key2.path[i]) return false;
}
return true;
}
These solutions seem to work, but are kinda ugly to have laying around. Is there just a built in function I'm missing?
Upvotes: 1
Views: 215
Reputation: 4303
You are not missing anything. There is no built in implementation of the key comparsion for datastore. I believe this is because it might be highly depends from business logic.
I'm using this implementation.
/**
* Compare two keys on equality
* @param {Object} key1
* @param {Object} key2
* @return {boolean}
*/
function compareKeys (key1, key2) {
return key1.namespace === key2.namespace && _.isEqual(key1.path, key2.path);
}
Update
I've created simple npm module in order to not copy/paste such solution everywhere.
https://www.npmjs.com/package/datastore-key-compare
Upvotes: 1