Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

datastore: assign appropriate ID or name attribute #880

Merged
merged 1 commit into from
Sep 21, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions lib/datastore/entity.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@

'use strict';

var is = require('is');

/** @const {object} Map for query operation -> operation protocol value. */
var OP_TO_OPERATOR = {
'=': 'EQUAL',
Expand Down Expand Up @@ -223,11 +225,10 @@ function keyToKeyProto(key) {
var p = { kind: keyPath[i] };
var val = keyPath[i + 1];
if (val) {
// if not numeric, set key name.
if (isNaN(val)) {
p.name = val;
} else {
if (is.number(val)) {
p.id = val;
} else {
p.name = val;
}
} else if (i < keyPath.length - 2) { // i is second last path item
throw new Error('Invalid key. Ancestor keys require an id or name.');
Expand Down
17 changes: 14 additions & 3 deletions test/datastore/entity.js
Original file line number Diff line number Diff line change
Expand Up @@ -192,12 +192,20 @@ describe('keyToKeyProto', function() {
it('should handle incomplete keys with & without namespaces', function() {
var key = new entity.Key({ path: [ 'Kind1' ] });
var keyWithNS = new entity.Key({
namespace: 'Namespace',
path: [ 'Kind1' ]
});
namespace: 'Namespace',
path: [ 'Kind1' ]
});
var keyWithNumericID = new entity.Key({
path: [ 'Kind1', 234 ]
});
var keyWithStringID = new entity.Key({
path: [ 'Kind1', 'StringId' ]
});

var proto = entity.keyToKeyProto(key);
var protoWithNS = entity.keyToKeyProto(keyWithNS);
var protoWithNumericID = entity.keyToKeyProto(keyWithNumericID);
var protoWithStringID = entity.keyToKeyProto(keyWithStringID);

assert.strictEqual(proto.partition_id, undefined);
assert.strictEqual(proto.path_element[0].kind, 'Kind1');
Expand All @@ -208,6 +216,9 @@ describe('keyToKeyProto', function() {
assert.strictEqual(protoWithNS.path_element[0].kind, 'Kind1');
assert.strictEqual(protoWithNS.path_element[0].id, undefined);
assert.strictEqual(protoWithNS.path_element[0].name, undefined);

assert.strictEqual(protoWithNumericID.path_element[0].id, 234);
assert.strictEqual(protoWithStringID.path_element[0].name, 'StringId');
});

it('should throw if key contains 0 items', function() {
Expand Down