-
Notifications
You must be signed in to change notification settings - Fork 106
/
index.ts
1909 lines (1800 loc) · 55.9 KB
/
index.ts
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
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* Copyright 2018 Google LLC.
*
* 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.
*/
/**
* @namespace google
*/
/**
* @namespace google.datastore.v1
*/
/**
* @namespace google.protobuf
*/
import arrify = require('arrify');
import extend = require('extend');
import {
GrpcClient,
ClientStub,
ChannelCredentials,
GoogleAuth,
GoogleAuthOptions,
CallOptions,
Operation,
ServiceError,
} from 'google-gax';
import * as is from 'is';
import {Transform, pipeline} from 'stream';
import {entity, Entities, Entity, EntityProto, ValueProto} from './entity';
import {AggregateField} from './aggregate';
import Key = entity.Key;
export {Entity, Key, AggregateField};
import {PropertyFilter, and, or} from './filter';
export {PropertyFilter, and, or};
import {
GetIndexesCallback,
GetIndexesOptions,
GetIndexesResponse,
IIndex,
Index,
} from './index-class';
import {Query} from './query';
import {
DatastoreRequest,
CommitCallback,
CommitResponse,
PrepareEntityObjectResponse,
SaveCallback,
SaveResponse,
Mutation,
RequestOptions,
} from './request';
import {Transaction} from './transaction';
import {promisifyAll} from '@google-cloud/promisify';
import {google} from '../protos/protos';
import {AggregateQuery} from './aggregate';
const {grpc} = new GrpcClient();
export type PathType = string | number | entity.Int;
export interface BooleanObject {
[key: string]: boolean;
}
export interface EntityProtoReduceAccumulator {
[key: string]: ValueProto;
}
export interface EntityProtoReduceData {
value: ValueProto;
excludeFromIndexes: ValueProto;
name: string | number;
}
export type UpdateCallback = CommitCallback;
export type UpdateResponse = CommitResponse;
export type UpsertCallback = CommitCallback;
export type UpsertResponse = CommitResponse;
export type InsertCallback = CommitCallback;
export type InsertResponse = CommitResponse;
export interface LongRunningCallback {
(
err: ServiceError | null,
operation?: Operation,
apiResponse?: google.longrunning.IOperation
): void;
}
export type LongRunningResponse = [Operation, google.longrunning.IOperation];
export interface ExportEntitiesConfig
extends Omit<google.datastore.admin.v1.IExportEntitiesRequest, 'projectId'> {
bucket?: string | {name: string};
kinds?: string[];
namespaces?: string[];
gaxOptions?: CallOptions;
}
export interface ImportEntitiesConfig
extends Omit<google.datastore.admin.v1.IImportEntitiesRequest, 'projectId'> {
file?: string | {bucket: {name: string}; name: string};
kinds?: string[];
namespaces?: string[];
gaxOptions?: CallOptions;
}
// Import the clients for each version supported by this package.
const gapic = Object.freeze({
v1: require('./v1'),
});
const urlSafeKey = new entity.URLSafeKey();
/**
* Idiomatic class for interacting with Cloud Datastore. Uses the lower-level
* {@link DatastoreClient} class under the hood.
*
* In addition to the constructor options shown here, the {@link Datastore}
* class constructor accepts the same options accepted by
* {@link DatastoreClient}.
*
* <h4>The Datastore Emulator</h4>
*
* Make sure you have the <a href="https://cloud.google.com/sdk/downloads">
* gcloud SDK installed</a>, then run:
*
* <pre>
* $ gcloud beta emulators datastore start --no-legacy
* </pre>
*
* You will see the following printed:
*
* <pre>
* [datastore] API endpoint: http://localhost:8005
* [datastore] If you are using a library that supports the
* DATASTORE_EMULATOR_HOST environment variable, run:
* [datastore]
* [datastore] export DATASTORE_EMULATOR_HOST=localhost:8005
* [datastore]
* [datastore] Dev App Server is now running.
* </pre>
*
* Set that environment variable and your localhost Datastore will
* automatically be used. You can also pass this address in manually with
* `apiEndpoint`.
*
* Additionally, `DATASTORE_PROJECT_ID` is recognized. If you have this set,
* you don't need to provide a `projectId`.
*
*
* See {@link https://cloud.google.com/datastore/docs/concepts/overview| Cloud Datastore Concepts Overview}
*
* @param {object} [options] Configuration options.
* @param {string} [options.apiEndpoint] Override the default API endpoint used
* to reach Datastore. This is useful for connecting to your local Datastore
* server (usually "http://localhost:8080").
* @param {string} [options.namespace] Namespace to isolate transactions to.
*
* @example Import the client library
* ```
* const {Datastore} = require('@google-cloud/datastore');
*
* ```
* @example Create a client that uses <a href="https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application">Application Default Credentials (ADC)</a>:
* ```
* const datastore = new Datastore();
*
* ```
* @example Create a client with <a href="https://cloud.google.com/docs/authentication/production#obtaining_and_providing_service_account_credentials_manually">explicit credentials</a>:
* ```
* const datastore = new Datastore({
* projectId: 'your-project-id',
* keyFilename: '/path/to/keyfile.json'
* });
*
* ```
* @example Retrieving Records
* ```
* const {Datastore} = require('@google-cloud/datastore');
* const datastore = new Datastore();
*
* // Records, called "entities" in Datastore, are retrieved by using a key. The
* // key is more than a numeric identifier, it is a complex data structure that
* // can be used to model relationships. The simplest key has a string `kind`
* // value, and either a numeric `id` value, or a string `name` value.
* //
* // A single record can be retrieved with {@link Datastore#key} and
* // {@link Datastore#get}.
* //-
* const key = datastore.key(['Company', 'Google']);
*
* datastore.get(key, function(err, entity) {
* // entity = The record.
* // entity[datastore.KEY] = The key for this entity.
* });
*
* //-
* // <h3>Querying Records</h3>
* //
* // Create a query with {@link Datastore#createQuery}.
* //-
* const query = datastore.createQuery('Company');
*
* //-
* // Multiple records can be found that match criteria with
* // {@link Query#filter}.
* //-
* query.filter('location', 'CA');
*
* //-
* // Records can also be ordered with {@link Query#order}.
* //-
* query.order('name');
*
* //-
* // The number of records returned can be specified with
* // {@link Query#limit}.
* //-
* query.limit(5);
*
* //-
* // Records' key structures can also be queried with
* // {@link Query#hasAncestor}.
* //-
* const ancestorKey = datastore.key(['ParentCompany', 'Alphabet']);
*
* query.hasAncestor(ancestorKey);
*
* //-
* // Run the query with {@link Datastore#runQuery}.
* //-
* datastore.runQuery(query, (err, entities) => {
* // entities = An array of records.
*
* // Access the Key object for an entity.
* const firstEntityKey = entities[0][datastore.KEY];
* });
*
* ```
* @example Paginating Records
* ```
* // Imagine building a website that allows a user to sift through hundreds of
* // their contacts. You'll likely want to only display a subset of these at
* // once, so you set a limit.
* //-
* const express = require('express');
* const app = express();
*
* const NUM_RESULTS_PER_PAGE = 15;
*
* app.get('/contacts', (req, res) => {
* const query = datastore.createQuery('Contacts')
* .limit(NUM_RESULTS_PER_PAGE);
*
* if (req.query.nextPageCursor) {
* query.start(req.query.nextPageCursor);
* }
*
* datastore.runQuery(query, (err, entities, info) => {
* if (err) {
* // Error handling omitted.
* return;
* }
*
* // Respond to the front end with the contacts and the cursoring token
* // from the query we just ran.
* const frontEndResponse = {
* contacts: entities
* };
*
* // Check if more results may exist.
* if (info.moreResults !== datastore.NO_MORE_RESULTS) {
* frontEndResponse.nextPageCursor = info.endCursor;
* }
*
* res.render('contacts', frontEndResponse);
* });
* });
*
* ```
* @example Creating Records
* ```
* // New entities can be created and persisted with {@link Datastore#save}.
* // The entity must have a key to be saved. If you don't specify an
* // identifier for the key, one is generated for you.
* //
* // We will create a key with a `name` identifier, "Google".
* //-
* const key = datastore.key(['Company', 'Google']);
*
* const data = {
* name: 'Google',
* location: 'CA'
* };
*
* datastore.save({
* key: key,
* data: data
* }, (err) => {
* if (!err) {
* // Record saved successfully.
* }
* });
*
* //-
* // We can verify the data was saved by using {@link Datastore#get}.
* //-
* datastore.get(key, (err, entity) => {
* // entity = {
* // name: 'Google',
* // location: 'CA'
* // }
* });
*
* //-
* // If we want to update this record, we can modify the data object and re-
* // save it.
* //-
* data.symbol = 'GOOG';
*
* datastore.save({
* key: key, // defined above (datastore.key(['Company', 'Google']))
* data: data
* }, (err, entity) => {
* if (!err) {
* // Record updated successfully.
* }
* });
*
* ```
* @example Deleting Records
* ```
* // Entities can be removed from Datastore by passing the entity's key object
* // to {@link Datastore#delete}.
* //-
* const key = datastore.key(['Company', 'Google']);
*
* datastore.delete(key, (err) => {
* if (!err) {
* // Record deleted successfully.
* }
* });
*
* ```
* @example Transactions
* ```
* // Complex logic can be wrapped in a transaction with
* // {@link Datastore#transaction}. All queries and updates run within
* // the transaction will be applied when the `done` function is called.
* //-
* const transaction = datastore.transaction();
*
* transaction.run((err) => {
* if (err) {
* // Error handling omitted.
* }
*
* const key = datastore.key(['Company', 'Google']);
*
* transaction.get(key, (err, entity) => {
* if (err) {
* // Error handling omitted.
* }
*
* entity.symbol = 'GOOG';
*
* transaction.save(entity);
*
* transaction.commit((err) => {
* if (!err) {
* // Transaction committed successfully.
* }
* });
* });
* });
*
* ```
* @example Queries with Ancestors
* ```
* const {Datastore} = require('@google-cloud/datastore');
* const datastore = new Datastore();
*
* const customerId1 = 2993844;
* const customerId2 = 4993882;
* const customerKey1 = datastore.key(['Customer', customerId1]);
* const customerKey2 = datastore.key(['Customer', customerId2]);
* const cookieKey1 = datastore.key(['Customer', customerId1, 'Cookie',
* 'cookie28839']); // child entity const cookieKey2 =
* datastore.key(['Customer', customerId1, 'Cookie', 'cookie78984']); // child
* entity const cookieKey3 = datastore.key(['Customer', customerId2, 'Cookie',
* 'cookie93911']); // child entity
*
* const entities = [];
*
* entities.push({
* key: customerKey1,
* data: {
* name: 'Jane Doe',
* address: '4848 Liller'
* }
* });
*
* entities.push({
* key: customerKey2,
* data: {
* name: 'John Smith',
* address: '4848 Pine'
* }
* });
*
* entities.push({
* key: cookieKey1,
* data: {
* cookieVal: 'dj83kks88rkld'
* }
* });
*
* entities.push({
* key: cookieKey2,
* data: {
* cookieVal: 'sj843ka99s'
* }
* });
*
* entities.push({
* key: cookieKey3,
* data: {
* cookieVal: 'otk82k2kw'
* }
* });
*
* datastore.upsert(entities);
*
* const query = datastore.createQuery().hasAncestor(customerKey1);
*
* datastore.runQuery(query, (err, entities) => {
* for (let entity of entities) {
* console.log(entity[datastore.KEY]);
* }
* });
*
* const query2 = datastore.createQuery().hasAncestor(customerKey2);
*
* datastore.runQuery(query2, (err, entities) => {
* for (let entity of entities) {
* console.log(entity[datastore.KEY]);
* }
* });
*
* datastore.runQuery(query2, (entities) => {
* console.log(entities);
* });
* ```
*/
class Datastore extends DatastoreRequest {
clients_: Map<string, ClientStub>;
namespace?: string;
defaultBaseUrl_: string;
options: DatastoreOptions;
baseUrl_?: string;
port_?: number;
customEndpoint_?: boolean;
auth: GoogleAuth;
constructor(options?: DatastoreOptions) {
super();
options = options || {};
this.clients_ = new Map();
this.datastore = this;
/**
* @name Datastore#namespace
* @type {string}
*/
this.namespace = options.namespace;
options.projectId = options.projectId || process.env.DATASTORE_PROJECT_ID;
this.defaultBaseUrl_ = 'datastore.googleapis.com';
this.determineBaseUrl_(options.apiEndpoint);
const scopes: string[] = Array.from(
new Set([
...gapic.v1.DatastoreClient.scopes,
...gapic.v1.DatastoreAdminClient.scopes,
])
);
this.options = Object.assign(
{
libName: 'gccl',
libVersion: require('../../package.json').version,
scopes,
servicePath: this.baseUrl_,
port: typeof this.port_ === 'number' ? this.port_ : 443,
},
options
);
const isUsingEmulator =
this.baseUrl_ &&
(this.baseUrl_.includes('localhost') ||
this.baseUrl_.includes('127.0.0.1') ||
this.baseUrl_.includes('::1'));
if (this.customEndpoint_ && isUsingEmulator) {
this.options.sslCreds ??= grpc.credentials.createInsecure();
}
this.auth = new GoogleAuth(this.options);
}
/**
* Create an aggregation query from a Query.
*
* @param {Query} query A Query object.
*/
createAggregationQuery(query: Query): AggregateQuery {
return new AggregateQuery(query);
}
/**
* Export entities from this project to a Google Cloud Storage bucket.
*
* @param {ExportEntitiesConfig} config Configuration object.
* @param {string | Bucket} config.bucket The `gs://bucket` path or a
* @google-cloud/storage Bucket object.
* @param {string[]} [config.kinds] The kinds to include in this import.
* @param {string[]} [config.namespaces] The namespace IDs to include in this
* import.
* @param {object} [config.gaxOptions] Request configuration options, outlined
* here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
* @param {function} callback The callback function.
* @param {?error} callback.err An error returned while making this request.
* @param {Operation} callback.operation An operation object that can be used
* to check the status of the request.
*/
export(config: ExportEntitiesConfig): Promise<LongRunningResponse>;
export(config: ExportEntitiesConfig, callback: LongRunningCallback): void;
export(
config: ExportEntitiesConfig,
callback?: LongRunningCallback
): void | Promise<LongRunningResponse> {
const reqOpts: ExportEntitiesConfig = {
entityFilter: {},
...config,
};
if (reqOpts.bucket && reqOpts.outputUrlPrefix) {
throw new Error('Both `bucket` and `outputUrlPrefix` were provided.');
}
if (!reqOpts.outputUrlPrefix) {
if (typeof config.bucket === 'string') {
reqOpts.outputUrlPrefix = `gs://${config.bucket.replace('gs://', '')}`;
} else if (typeof config.bucket === 'object') {
reqOpts.outputUrlPrefix = `gs://${config.bucket.name}`;
} else {
throw new Error('A Bucket object or URL must be provided.');
}
}
if (reqOpts.kinds) {
if (typeof config.entityFilter === 'object') {
throw new Error('Both `entityFilter` and `kinds` were provided.');
}
reqOpts.entityFilter!.kinds = reqOpts.kinds;
}
if (reqOpts.namespaces) {
if (typeof config.entityFilter === 'object') {
throw new Error('Both `entityFilter` and `namespaces` were provided.');
}
reqOpts.entityFilter!.namespaceIds = reqOpts.namespaces;
}
delete reqOpts.bucket;
delete reqOpts.gaxOptions;
delete reqOpts.kinds;
delete reqOpts.namespaces;
this.request_(
{
client: 'DatastoreAdminClient',
method: 'exportEntities',
reqOpts: reqOpts as RequestOptions,
gaxOpts: config.gaxOptions,
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
callback as any
);
}
/**
* Get all of the indexes in this project.
*
* @param {GetIndexesOptions | GetIndexesCallback} [optionsOrCallback]
* @param {object} [options.gaxOptions] Request configuration options,
* outlined here:
* https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
* @param {GetIndexesResponse} [callback] The callback function.
* @param {?error} callback.error An error returned while making this request.
* @param {Index[]} callback.indexes All matching Index instances.
* @param {object} callback.apiResponse The full API response.
* @return {void | Promise<GetIndexesResponse>}
*/
getIndexes(options?: GetIndexesOptions): Promise<GetIndexesResponse>;
getIndexes(options: GetIndexesOptions, callback: GetIndexesCallback): void;
getIndexes(callback: GetIndexesCallback): void;
getIndexes(
optionsOrCallback?: GetIndexesOptions | GetIndexesCallback,
cb?: GetIndexesCallback
): void | Promise<GetIndexesResponse> {
let options =
typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
const callback =
typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!;
options = extend(true, {}, options);
const gaxOpts = options.gaxOptions || {};
const reqOpts = {
pageSize: (gaxOpts as GetIndexesOptions).pageSize,
pageToken: (gaxOpts as GetIndexesOptions).pageToken,
...options,
};
delete (gaxOpts as GetIndexesOptions).pageSize;
delete (gaxOpts as GetIndexesOptions).pageToken;
delete (reqOpts as CallOptions).autoPaginate;
delete (reqOpts as GetIndexesOptions).gaxOptions;
if (
typeof options.autoPaginate === 'boolean' &&
typeof gaxOpts.autoPaginate === 'undefined'
) {
gaxOpts.autoPaginate = options.autoPaginate;
}
this.request_(
{
client: 'DatastoreAdminClient',
method: 'listIndexes',
reqOpts,
gaxOpts,
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(err, ...resp: any[]) => {
let indexes: Index[] = [];
if (resp[0]) {
indexes = resp[0].map((index: IIndex) => {
const indexInstance = this.index(index.indexId!);
indexInstance.metadata = index;
return indexInstance;
});
}
const nextQuery = resp[1]! ? Object.assign(options, resp[1]) : null;
const apiResp: google.datastore.admin.v1.IListIndexesResponse = resp[2];
callback(err as ServiceError, indexes, nextQuery, apiResp);
}
);
}
/**
* Get all of the indexes in this project as a readable object stream.
*
* @param {GetIndexesOptions} [options] Configuration object. See
* {@link Datastore#getIndexes} for a complete list of options.
* @returns {ReadableStream<Index>}
*/
getIndexesStream(options?: GetIndexesOptions): NodeJS.ReadableStream {
const {gaxOptions, ...reqOpts} = options || {};
return pipeline(
this.requestStream_({
client: 'DatastoreAdminClient',
method: 'listIndexesStream',
reqOpts,
gaxOpts: gaxOptions,
}),
new Transform({
objectMode: true,
transform: (index: IIndex, enc: string, next: Function) => {
const indexInstance = this.index(index.indexId!);
indexInstance.metadata = index;
next(null, indexInstance);
},
}),
() => {}
);
}
getProjectId(): Promise<string> {
return this.auth.getProjectId();
}
/**
* Import entities into this project from a remote file.
*
* @param {ImportEntitiesConfig} config Configuration object.
* @param {string | File} config.file The `gs://bucket/file` path or a
* @google-cloud/storage File object.
* @param {string[]} [config.kinds] The kinds to include in this import.
* @param {string[]} [config.namespaces] The namespace IDs to include in this
* import.
* @param {object} [config.gaxOptions] Request configuration options, outlined
* here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
* @param {function} callback The callback function.
* @param {?error} callback.err An error returned while making this request.
* @param {Operation} callback.operation An operation object that can be used
* to check the status of the request.
*/
import(config: ImportEntitiesConfig): Promise<LongRunningResponse>;
import(config: ImportEntitiesConfig, callback: LongRunningCallback): void;
import(
config: ImportEntitiesConfig,
callback?: LongRunningCallback
): void | Promise<LongRunningResponse> {
const reqOpts: ImportEntitiesConfig = {
entityFilter: {},
...config,
};
if (config.file && config.inputUrl) {
throw new Error('Both `file` and `inputUrl` were provided.');
}
if (!reqOpts.inputUrl) {
if (typeof config.file === 'string') {
reqOpts.inputUrl = `gs://${config.file.replace('gs://', '')}`;
} else if (typeof config.file === 'object') {
reqOpts.inputUrl = `gs://${config.file.bucket.name}/${config.file.name}`;
} else {
throw new Error('An input URL must be provided.');
}
}
if (reqOpts.kinds) {
if (typeof config.entityFilter === 'object') {
throw new Error('Both `entityFilter` and `kinds` were provided.');
}
reqOpts.entityFilter!.kinds = reqOpts.kinds;
}
if (reqOpts.namespaces) {
if (typeof config.entityFilter === 'object') {
throw new Error('Both `entityFilter` and `namespaces` were provided.');
}
reqOpts.entityFilter!.namespaceIds = reqOpts.namespaces;
}
delete reqOpts.file;
delete reqOpts.gaxOptions;
delete reqOpts.kinds;
delete reqOpts.namespaces;
this.request_(
{
client: 'DatastoreAdminClient',
method: 'importEntities',
reqOpts: reqOpts as RequestOptions,
gaxOpts: config.gaxOptions,
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
callback as any
);
}
/**
* Get a reference to an Index.
*
* @param {string} id The index name or id.
* @returns {Index}
*/
index(id: string): Index {
return new Index(this, id);
}
/**
* Maps to {@link https://cloud.google.com/nodejs/docs/reference/datastore/latest/datastore/datastore#_google_cloud_datastore_Datastore_save_member_1_|Datastore#save}, forcing the method to be `insert`.
*
* @param {object|object[]} entities Datastore key object(s).
* @param {Key} entities.key Datastore key object.
* @param {string[]} [entities.excludeFromIndexes] Exclude properties from
* indexing using a simple JSON path notation. See the examples in
* {@link Datastore#save} to see how to target properties at different
* levels of nesting within your entity.
* @param {object} entities.data Data to save with the provided key.
* @param {function} callback The callback function.
* @param {?error} callback.err An error returned while making this request
* @param {object} callback.apiResponse The full API response.
*/
insert(entities: Entities): Promise<InsertResponse>;
insert(entities: Entities, callback: InsertCallback): void;
insert(
entities: Entities,
callback?: InsertCallback
): void | Promise<InsertResponse> {
entities = arrify(entities)
.map(DatastoreRequest.prepareEntityObject_)
.map((x: PrepareEntityObjectResponse) => {
x.method = 'insert';
return x;
});
this.save(entities, callback!);
}
/**
* Insert or update the specified object(s). If a key is incomplete, its
* associated object is inserted and the original Key object is updated to
* contain the generated ID.
*
* This method will determine the correct Datastore method to execute
* (`upsert`, `insert`, or `update`) by using the key(s) provided. For
* example, if you provide an incomplete key (one without an ID), the request
* will create a new entity and have its ID automatically assigned. If you
* provide a complete key, the entity will be updated with the data specified.
*
* By default, all properties are indexed. To prevent a property from being
* included in *all* indexes, you must supply an `excludeFromIndexes` array.
*
* To prevent large properties from being included in *all* indexes, you must supply
* `excludeLargeProperties: true`.
* See below for an example.
*
* @borrows {@link Transaction#save} as save
*
* @throws {Error} If an unrecognized method is provided.
*
* @param {object|object[]} entities Datastore key object(s).
* @param {Key} entities.key Datastore key object.
* @param {string[]} [entities.excludeFromIndexes] Exclude properties from
* indexing using a simple JSON path notation. See the example below to
* see how to target properties at different levels of nesting within your
* @param {boolean} [entities.excludeLargeProperties] Automatically exclude
* large properties from indexing. It help in storing large values.
* @param {string} [entities.method] Explicit method to use, either 'insert',
* 'update', or 'upsert'.
* @param {object} entities.data Data to save with the provided key.
* entity.
* @param {object} [gaxOptions] Request configuration options, outlined here:
* https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
* @param {function} callback The callback function.
* @param {?error} callback.err An error returned while making this request
* @param {object} callback.apiResponse The full API response.
*
* @example
* ```
* //-
* // Save a single entity.
* //
* // Notice that we are providing an incomplete key. After saving, the
* // original Key object used to save will be updated to contain the path
* // with its generated ID.
* //-
* const key = datastore.key('Company');
* const entity = {
* key: key,
* data: {
* rating: '10'
* }
* };
*
* datastore.save(entity, (err) => {
* console.log(key.path); // [ 'Company', 5669468231434240 ]
* console.log(key.namespace); // undefined
* });
*
* //-
* // Save a single entity using a provided name instead of auto-generated ID.
* //
* // Here we are providing a key with name instead of an ID. After saving,
* // the original Key object used to save will be updated to contain the
* // path with the name instead of a generated ID.
* //-
* const key = datastore.key(['Company', 'donutshack']);
* const entity = {
* key: key,
* data: {
* name: 'DonutShack',
* rating: 8
* }
* };
*
* datastore.save(entity, (err) => {
* console.log(key.path); // ['Company', 'donutshack']
* console.log(key.namespace); // undefined
* });
*
* //-
* // Save a single entity with a provided namespace. Namespaces allow for
* // multitenancy. To read more about this, see
* // [the Datastore docs on key concepts](https://goo.gl/M1LUAu).
* //
* // Here we are providing a key with namespace.
* //-
* const key = datastore.key({
* namespace: 'my-namespace',
* path: ['Company', 'donutshack']
* });
*
* const entity = {
* key: key,
* data: {
* name: 'DonutShack',
* rating: 8
* }
* };
*
* datastore.save(entity, (err) => {
* console.log(key.path); // ['Company', 'donutshack']
* console.log(key.namespace); // 'my-namespace'
* });
*
* //-
* // Save different types of data, including ints, doubles, dates, booleans,
* // blobs, and lists.
* //
* // Notice that we are providing an incomplete key. After saving, the
* // original Key object used to save will be updated to contain the path
* // with its generated ID.
* //-
* const key = datastore.key('Company');
* const entity = {
* key: key,
* data: {
* name: 'DonutShack',
* rating: datastore.int(10),
* worth: datastore.double(123456.78),
* location: datastore.geoPoint({
* latitude: 40.6894,
* longitude: -74.0447
* }),
* numDonutsServed: 45,
* founded: new Date('Tue May 12 2015 15:30:00 GMT-0400 (EDT)'),
* isStartup: true,
* donutEmoji: Buffer.from('\uD83C\uDF69'),
* keywords: [
* 'donut',
* 'coffee',
* 'yum'
* ]
* }
* };
*
* datastore.save(entity, (err, apiResponse) => {});
*
* //-
* // Use an array, `excludeFromIndexes`, to exclude properties from indexing.
* // This will allow storing string values larger than 1500 bytes.
* //-
* const entity = {
* key: datastore.key('Company'),
* excludeFromIndexes: [
* 'description',
* 'embeddedEntity.description',
* 'arrayValue[]',
* 'arrayValue[].description'
* ],
* data: {
* description: 'Long string (...)',
* embeddedEntity: {
* description: 'Long string (...)'
* },
* arrayValue: [
* 'Long string (...)',
* {
* description: 'Long string (...)'
* }
* ]
* }
* };
*
* datastore.save(entity, (err, apiResponse) => {});
*
* //-
* // Use boolean `excludeLargeProperties`, to auto exclude Large properties from indexing.
* // This will allow storing string values larger than 1500 bytes.
* //-
* const entity = {
* key: datastore.key('Company'),
* data: {
* description: 'Long string (...)',
* embeddedEntity: {
* description: 'Long string (...)'
* },
* arrayValue: [
* 'Long string (...)',
* {