-
Notifications
You must be signed in to change notification settings - Fork 581
/
entity.js
797 lines (680 loc) · 16.4 KB
/
entity.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
/**
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @private
* @module datastore/entity
*/
'use strict';
var arrify = require('arrify');
var createErrorClass = require('create-error-class');
var extend = require('extend');
var is = require('is');
var entity = module.exports;
var InvalidKeyError = createErrorClass('InvalidKey', function(opts) {
var errorMessages = {
MISSING_KIND: 'A key should contain at least a kind.',
MISSING_ANCESTOR_ID: 'Ancestor keys require an id or name.'
};
this.message = errorMessages[opts.code];
});
/**
* A symbol to access the Key object from an entity object.
*
* @type {symbol}
*/
entity.KEY_SYMBOL = Symbol('KEY');
/**
* Build a Datastore Double object. For long doubles, a string can be provided.
*
* @constructor
* @param {number} value - The double value.
*
* @example
* var aDouble = new Double(7.3);
*/
function Double(value) {
this.value = value;
}
entity.Double = Double;
/**
* Check if something is a Datastore Double object.
*
* @param {*} value
* @return {boolean}
*/
function isDsDouble(value) {
return value instanceof entity.Double;
}
entity.isDsDouble = isDsDouble;
/**
* Build a Datastore Int object. For long integers, a string can be provided.
*
* @constructor
* @param {number|string} value - The integer value.
*
* @example
* var anInt = new Int(7);
*/
function Int(value) {
this.value = value.toString();
}
entity.Int = Int;
/**
* Check if something is a Datastore Int object.
*
* @param {*} value
* @return {boolean}
*/
function isDsInt(value) {
return value instanceof entity.Int;
}
entity.isDsInt = isDsInt;
/**
* Build a Datastore Geo Point object.
*
* @constructor
* @param {object} coordinates - Coordinate value.
* @param {number} coordinates.latitude - Latitudinal value.
* @param {number} coordinates.longitude - Longitudinal value.
*
* @example
* var coordinates = {
* latitude: 40.6894,
* longitude: -74.0447
* };
*
* var geoPoint = new GeoPoint(coordinates);
*/
function GeoPoint(coordinates) {
this.value = coordinates;
}
entity.GeoPoint = GeoPoint;
/**
* Check if something is a Datastore Geo Point object.
*
* @param {*} value
* @return {boolean}
*/
function isDsGeoPoint(value) {
return value instanceof entity.GeoPoint;
}
entity.isDsGeoPoint = isDsGeoPoint;
/**
* Build a Datastore Key object.
*
* @constructor
* @param {object} - Configuration object.
* @param {...*} options.path - Key path.
* @param {string=} options.namespace - Optional namespace.
*
* @example
* var key = new Key({
* namespace: 'ns',
* path: ['Company', 123]
* });
*/
function Key(options) {
this.namespace = options.namespace;
if (options.path.length % 2 === 0) {
var identifier = options.path.pop();
if (is.number(identifier) || isDsInt(identifier)) {
this.id = identifier.value || identifier;
} else if (is.string(identifier)) {
this.name = identifier;
}
}
this.kind = options.path.pop();
if (options.path.length > 0) {
this.parent = new Key(options);
}
// `path` is computed on demand to consider any changes that may have been
// made to the key.
Object.defineProperty(this, 'path', {
enumerable: true,
get: function() {
return arrify(this.parent && this.parent.path)
.concat([this.kind, this.name || this.id]);
}
});
}
entity.Key = Key;
/**
* Check if something is a Datastore Key object.
*
* @param {*} value
* @return {boolean}
*/
function isDsKey(value) {
return value instanceof entity.Key;
}
entity.isDsKey = isDsKey;
/**
* Convert a protobuf Value message to its native value.
*
* @param {object} valueProto - The protobuf Value message to convert.
* @return {*}
*
* @example
* decodeValueProto({
* booleanValue: false
* });
* // false
*
* decodeValueProto({
* stringValue: 'Hi'
* });
* // 'Hi'
*
* decodeValueProto({
* blobValue: new Buffer('68656c6c6f')
* });
* // <Buffer 68 65 6c 6c 6f>
*/
function decodeValueProto(valueProto) {
var valueType = valueProto.value_type;
var value = valueProto[valueType];
switch (valueType) {
case 'arrayValue': {
return value.values.map(entity.decodeValueProto);
}
case 'blobValue': {
return new Buffer(value, 'base64');
}
case 'nullValue': {
return null;
}
case 'doubleValue': {
return parseFloat(value, 10);
}
case 'integerValue': {
return parseInt(value, 10);
}
case 'entityValue': {
return entity.entityFromEntityProto(value);
}
case 'keyValue': {
return entity.keyFromKeyProto(value);
}
case 'timestampValue': {
var milliseconds = parseInt(value.nanos, 10) / 1e6;
return new Date(parseInt(value.seconds, 10) * 1000 + milliseconds);
}
default: {
return value;
}
}
}
entity.decodeValueProto = decodeValueProto;
/**
* Convert any native value to a protobuf Value message object.
*
* @param {*} value - Native value.
* @return {object}
*
* @example
* encodeValue('Hi');
* // {
* // stringValue: 'Hi'
* // }
*/
function encodeValue(value) {
var valueProto = {};
if (is.boolean(value)) {
valueProto.booleanValue = value;
return valueProto;
}
if (is.nil(value)) {
valueProto.nullValue = 0;
return valueProto;
}
if (is.number(value)) {
if (value % 1 === 0) {
value = new entity.Int(value);
} else {
value = new entity.Double(value);
}
}
if (isDsInt(value)) {
valueProto.integerValue = value.value;
return valueProto;
}
if (isDsDouble(value)) {
valueProto.doubleValue = value.value;
return valueProto;
}
if (isDsGeoPoint(value)) {
valueProto.geoPointValue = value.value;
return valueProto;
}
if (value instanceof Date) {
var seconds = value.getTime() / 1000;
valueProto.timestampValue = {
seconds: Math.floor(seconds),
nanos: value.getMilliseconds() * 1e6
};
return valueProto;
}
if (is.string(value)) {
valueProto.stringValue = value;
return valueProto;
}
if (value instanceof Buffer) {
valueProto.blobValue = value;
return valueProto;
}
if (is.array(value)) {
valueProto.arrayValue = {
values: value.map(entity.encodeValue)
};
return valueProto;
}
if (isDsKey(value)) {
valueProto.keyValue = entity.keyToKeyProto(value);
return valueProto;
}
if (is.object(value)) {
if (!is.empty(value)) {
value = extend(true, {}, value);
for (var prop in value) {
if (value.hasOwnProperty(prop)) {
value[prop] = entity.encodeValue(value[prop]);
}
}
}
valueProto.entityValue = {
properties: value
};
return valueProto;
}
throw new Error('Unsupported field value, ' + value + ', was provided.');
}
entity.encodeValue = encodeValue;
/**
* Convert any entity protocol to a plain object.
*
* @todo Use registered metadata if provided.
*
* @param {object} entityProto - The protocol entity object to convert.
* @return {object}
*
* @example
* entityFromEntityProto({
* properties: {
* map: {
* name: {
* value: {
* value_type: 'stringValue',
* stringValue: 'Stephen'
* }
* }
* }
* }
* });
* // {
* // name: 'Stephen'
* // }
*/
function entityFromEntityProto(entityProto) {
var entityObject = {};
var properties = entityProto.properties || {};
for (var property in properties) {
var value = properties[property];
entityObject[property] = entity.decodeValueProto(value);
}
return entityObject;
}
entity.entityFromEntityProto = entityFromEntityProto;
/**
* Convert an entity object to an entity protocol object.
*
* @param {object} entityObject - The entity object to convert.
* @return {object}
*
* @example
* entityToEntityProto({
* excludeFromIndexes: [
* 'name'
* ],
* data: {
* name: 'Burcu',
* legit: true
* }
* });
* // {
* // key: null,
* // properties: {
* // name: {
* // stringValue: 'Burcu'
* // excludeFromIndexes: true
* // },
* // legit: {
* // booleanValue: true
* // }
* // }
* // }
*/
function entityToEntityProto(entityObject) {
var properties = entityObject.data;
var excludeFromIndexes = entityObject.excludeFromIndexes;
var entityProto = {
key: null,
properties: Object.keys(properties).reduce(function(encoded, key) {
encoded[key] = entity.encodeValue(properties[key]);
return encoded;
}, {})
};
if (excludeFromIndexes && excludeFromIndexes.length > 0) {
excludeFromIndexes.forEach(function(excludePath) {
excludePathFromEntity(entityProto, excludePath);
});
}
return entityProto;
function excludePathFromEntity(entity, path) {
var arrayIndex = path.indexOf('[]');
var entityIndex = path.indexOf('.');
var hasArrayPath = arrayIndex > -1;
var hasEntityPath = entityIndex > -1;
if (!hasArrayPath && !hasEntityPath) {
if (entity.properties[path]) {
// This is the property to exclude!
entity.properties[path].excludeFromIndexes = true;
}
return;
}
var delimiterIndex;
if (hasArrayPath && hasEntityPath) {
delimiterIndex = Math.min(arrayIndex, entityIndex);
} else {
delimiterIndex = Math.max(arrayIndex, entityIndex);
}
var firstPathPartIsArray = delimiterIndex === arrayIndex;
var firstPathPartIsEntity = delimiterIndex === entityIndex;
var delimiter = firstPathPartIsArray ? '[]' : '.';
var splitPath = path.split(delimiter);
var firstPathPart = splitPath.shift();
var remainderPath = splitPath.join(delimiter).replace(/^(\.|[])/, '');
if (!entity.properties[firstPathPart]) {
return;
}
if (firstPathPartIsArray) {
var array = entity.properties[firstPathPart].arrayValue;
array.values.forEach(function(arrayValue) {
excludePathFromEntity(arrayValue.entityValue, remainderPath);
});
} else if (firstPathPartIsEntity) {
var parentEntity = entity.properties[firstPathPart].entityValue;
excludePathFromEntity(parentEntity, remainderPath);
}
}
}
entity.entityToEntityProto = entityToEntityProto;
/**
* Convert an API response array to a qualified Key and data object.
*
* @param {object[]} results - The response array.
* @param {object} results.entity - An entity object.
* @param {object} results.entity.key - The entity's key.
* @return {object[]}
*
* @example
* request_('runQuery', {}, function(err, response) {
* var entityObjects = formatArray(response.batch.entityResults);
* // {
* // key: {},
* // data: {
* // fieldName: 'value'
* // }
* // }
* //
* });
*/
function formatArray(results) {
return results.map(function(result) {
var ent = entity.entityFromEntityProto(result.entity);
ent[entity.KEY_SYMBOL] = entity.keyFromKeyProto(result.entity.key);
return ent;
});
}
entity.formatArray = formatArray;
/**
* Check if a key is complete.
*
* @param {Key} key - The Key object.
* @return {boolean}
*
* @example
* isKeyComplete(new Key(['Company', 'Google'])); // true
* isKeyComplete(new Key('Company')); // false
*/
function isKeyComplete(key) {
var lastPathElement = entity.keyToKeyProto(key).path.pop();
return !!(lastPathElement.id || lastPathElement.name);
}
entity.isKeyComplete = isKeyComplete;
/**
* Convert a key protocol object to a Key object.
*
* @param {object} keyProto - The key protocol object to convert.
* @return {Key}
*
* @example
* var key = keyFromKeyProto({
* partitionId: {
* projectId: 'project-id',
* namespaceId: ''
* },
* path: [
* {
* kind: 'Kind',
* id: '4790047639339008'
* }
* ]
* });
*/
function keyFromKeyProto(keyProto) {
var keyOptions = {
path: []
};
if (keyProto.partitionId && keyProto.partitionId.namespaceId) {
keyOptions.namespace = keyProto.partitionId.namespaceId;
}
keyProto.path.forEach(function(path, index) {
keyOptions.path.push(path.kind);
var id = path[path.id_type];
if (path.id_type === 'id') {
id = new entity.Int(id);
}
if (is.defined(id)) {
keyOptions.path.push(id);
} else if (index < keyProto.path.length - 1) {
throw new InvalidKeyError({
code: 'MISSING_ANCESTOR_ID'
});
}
});
return new entity.Key(keyOptions);
}
entity.keyFromKeyProto = keyFromKeyProto;
/**
* Convert a Key object to a key protocol object.
*
* @param {Key} key - The Key object to convert.
* @return {object}
*
* @example
* var keyProto = keyToKeyProto(new Key(['Company', 1]));
* // {
* // path: [
* // {
* // kind: 'Company',
* // id: 1
* // }
* // ]
* // }
*/
function keyToKeyProto(key) {
if (is.undefined(key.kind)) {
throw new InvalidKeyError({
code: 'MISSING_KIND'
});
}
var keyProto = {
path: []
};
if (key.namespace) {
keyProto.partitionId = {
namespaceId: key.namespace
};
}
var numKeysWalked = 0;
// Reverse-iterate over the Key objects.
do {
if (numKeysWalked > 0 && is.undefined(key.id) && is.undefined(key.name)) {
// This isn't just an incomplete key. An ancestor key is incomplete.
throw new InvalidKeyError({
code: 'MISSING_ANCESTOR_ID'
});
}
var pathElement = {
kind: key.kind
};
if (is.defined(key.id)) {
pathElement.id = key.id;
}
if (is.defined(key.name)) {
pathElement.name = key.name;
}
keyProto.path.unshift(pathElement);
} while ((key = key.parent) && ++numKeysWalked);
return keyProto;
}
entity.keyToKeyProto = keyToKeyProto;
/**
* Convert a query object to a query protocol object.
*
* @private
*
* @param {object} q - The query object to convert.
* @return {object}
*
* @example
* queryToQueryProto({
* namespace: '',
* kinds: [
* 'Kind'
* ],
* filters: [],
* orders: [],
* groupByVal: [],
* selectVal: [],
* startVal: null,
* endVal: null,
* limitVal: -1,
* offsetVal: -1
* });
* // {
* // projection: [],
* // kinds: [
* // {
* // name: 'Kind'
* // }
* // ],
* // order: [],
* // groupBy: []
* // }
*/
function queryToQueryProto(query) {
var OP_TO_OPERATOR = {
'=': 'EQUAL',
'>': 'GREATER_THAN',
'>=': 'GREATER_THAN_OR_EQUAL',
'<': 'LESS_THAN',
'<=': 'LESS_THAN_OR_EQUAL',
HAS_ANCESTOR: 'HAS_ANCESTOR'
};
var SIGN_TO_ORDER = {
'-': 'DESCENDING',
'+': 'ASCENDING'
};
var queryProto = {
distinctOn: query.groupByVal.map(function(groupBy) {
return {
name: groupBy
};
}),
kind: query.kinds.map(function(kind) {
return {
name: kind
};
}),
order: query.orders.map(function(order) {
return {
property: {
name: order.name
},
direction: SIGN_TO_ORDER[order.sign]
};
}),
projection: query.selectVal.map(function(select) {
return {
property: {
name: select
}
};
})
};
if (query.endVal) {
queryProto.endCursor = query.endVal;
}
if (query.limitVal > 0) {
queryProto.limit = {
value: query.limitVal
};
}
if (query.offsetVal > 0) {
queryProto.offset = query.offsetVal;
}
if (query.startVal) {
queryProto.startCursor = query.startVal;
}
if (query.filters.length > 0) {
var filters = query.filters.map(function(filter) {
var value = {};
if (filter.name === '__key__') {
value.keyValue = entity.keyToKeyProto(filter.val);
} else {
value = entity.encodeValue(filter.val);
}
return {
propertyFilter: {
property: {
name: filter.name
},
op: OP_TO_OPERATOR[filter.op],
value: value
}
};
});
queryProto.filter = {
compositeFilter: {
filters: filters,
op: 'AND'
}
};
}
return queryProto;
}
entity.queryToQueryProto = queryToQueryProto;