UNPKG

23 kBTypeScriptView Raw
1/*!
2 * Copyright 2018 Google LLC.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16/// <reference types="node" />
17import { ClientStub, ChannelCredentials, GoogleAuth, GoogleAuthOptions, CallOptions, Operation, ServiceError } from 'google-gax';
18import { entity, Entities, Entity, ValueProto } from './entity';
19import Key = entity.Key;
20export { Entity, Key };
21import { GetIndexesCallback, GetIndexesOptions, GetIndexesResponse, Index } from './index-class';
22import { Query } from './query';
23import { DatastoreRequest, CommitCallback, CommitResponse, SaveCallback, SaveResponse } from './request';
24import { Transaction } from './transaction';
25import { google } from '../protos/protos';
26export declare type PathType = string | number | entity.Int;
27export interface BooleanObject {
28 [key: string]: boolean;
29}
30export interface EntityProtoReduceAccumulator {
31 [key: string]: ValueProto;
32}
33export interface EntityProtoReduceData {
34 value: ValueProto;
35 excludeFromIndexes: ValueProto;
36 name: string | number;
37}
38export declare type UpdateCallback = CommitCallback;
39export declare type UpdateResponse = CommitResponse;
40export declare type UpsertCallback = CommitCallback;
41export declare type UpsertResponse = CommitResponse;
42export declare type InsertCallback = CommitCallback;
43export declare type InsertResponse = CommitResponse;
44export interface LongRunningCallback {
45 (err: ServiceError | null, operation?: Operation, apiResponse?: google.longrunning.IOperation): void;
46}
47export declare type LongRunningResponse = [Operation, google.longrunning.IOperation];
48export interface ExportEntitiesConfig extends Omit<google.datastore.admin.v1.IExportEntitiesRequest, 'projectId'> {
49 bucket?: string | {
50 name: string;
51 };
52 kinds?: string[];
53 namespaces?: string[];
54 gaxOptions?: CallOptions;
55}
56export interface ImportEntitiesConfig extends Omit<google.datastore.admin.v1.IImportEntitiesRequest, 'projectId'> {
57 file?: string | {
58 bucket: {
59 name: string;
60 };
61 name: string;
62 };
63 kinds?: string[];
64 namespaces?: string[];
65 gaxOptions?: CallOptions;
66}
67/**
68 * Idiomatic class for interacting with Cloud Datastore. Uses the lower-level
69 * {@link v1.DatastoreClient} class under the hood.
70 *
71 * In addition to the constructor options shown here, the {@link Datastore}
72 * class constructor accepts the same options accepted by
73 * {@link v1.DatastoreClient}.
74 *
75 * <h4>The Datastore Emulator</h4>
76 *
77 * Make sure you have the <a href="https://cloud.google.com/sdk/downloads">
78 * gcloud SDK installed</a>, then run:
79 *
80 * <pre>
81 * $ gcloud beta emulators datastore start --no-legacy
82 * </pre>
83 *
84 * You will see the following printed:
85 *
86 * <pre>
87 * [datastore] API endpoint: http://localhost:8005
88 * [datastore] If you are using a library that supports the
89 * DATASTORE_EMULATOR_HOST environment variable, run:
90 * [datastore]
91 * [datastore] export DATASTORE_EMULATOR_HOST=localhost:8005
92 * [datastore]
93 * [datastore] Dev App Server is now running.
94 * </pre>
95 *
96 * Set that environment variable and your localhost Datastore will
97 * automatically be used. You can also pass this address in manually with
98 * `apiEndpoint`.
99 *
100 * Additionally, `DATASTORE_PROJECT_ID` is recognized. If you have this set,
101 * you don't need to provide a `projectId`.
102 *
103 *
104 * @class
105 * @extends {DatastoreRequest}
106 *
107 * @see [Cloud Datastore Concepts Overview]{@link https://cloud.google.com/datastore/docs/concepts/overview}
108 *
109 * @param {object} [options] Configuration options.
110 * @param {string} [options.apiEndpoint] Override the default API endpoint used
111 * to reach Datastore. This is useful for connecting to your local Datastore
112 * server (usually "http://localhost:8080").
113 * @param {string} [options.namespace] Namespace to isolate transactions to.
114 *
115 * @example <caption>Import the client library</caption>
116 * const {Datastore} = require('@google-cloud/datastore');
117 *
118 * @example <caption>Create a client that uses <a href="https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application">Application Default Credentials (ADC)</a>:</caption>
119 * const datastore = new Datastore();
120 *
121 * @example <caption>Create a client with <a href="https://cloud.google.com/docs/authentication/production#obtaining_and_providing_service_account_credentials_manually">explicit credentials</a>:</caption>
122 * const datastore = new Datastore({
123 * projectId: 'your-project-id',
124 * keyFilename: '/path/to/keyfile.json'
125 * });
126 *
127 * @example <caption>Retrieving Records</caption>
128 * const {Datastore} = require('@google-cloud/datastore');
129 * const datastore = new Datastore();
130 *
131 * // Records, called "entities" in Datastore, are retrieved by using a key. The
132 * // key is more than a numeric identifier, it is a complex data structure that
133 * // can be used to model relationships. The simplest key has a string `kind`
134 * // value, and either a numeric `id` value, or a string `name` value.
135 * //
136 * // A single record can be retrieved with {@link Datastore#key} and
137 * // {@link Datastore#get}.
138 * //-
139 * const key = datastore.key(['Company', 'Google']);
140 *
141 * datastore.get(key, function(err, entity) {
142 * // entity = The record.
143 * // entity[datastore.KEY] = The key for this entity.
144 * });
145 *
146 * //-
147 * // <h3>Querying Records</h3>
148 * //
149 * // Create a query with {@link Datastore#createQuery}.
150 * //-
151 * const query = datastore.createQuery('Company');
152 *
153 * //-
154 * // Multiple records can be found that match criteria with
155 * // {@link Query#filter}.
156 * //-
157 * query.filter('location', 'CA');
158 *
159 * //-
160 * // Records can also be ordered with {@link Query#order}.
161 * //-
162 * query.order('name');
163 *
164 * //-
165 * // The number of records returned can be specified with
166 * // {@link Query#limit}.
167 * //-
168 * query.limit(5);
169 *
170 * //-
171 * // Records' key structures can also be queried with
172 * // {@link Query#hasAncestor}.
173 * //-
174 * const ancestorKey = datastore.key(['ParentCompany', 'Alphabet']);
175 *
176 * query.hasAncestor(ancestorKey);
177 *
178 * //-
179 * // Run the query with {@link Datastore#runQuery}.
180 * //-
181 * datastore.runQuery(query, (err, entities) => {
182 * // entities = An array of records.
183 *
184 * // Access the Key object for an entity.
185 * const firstEntityKey = entities[0][datastore.KEY];
186 * });
187 *
188 * @example <caption>Paginating Records</caption>
189 * // Imagine building a website that allows a user to sift through hundreds of
190 * // their contacts. You'll likely want to only display a subset of these at
191 * // once, so you set a limit.
192 * //-
193 * const express = require('express');
194 * const app = express();
195 *
196 * const NUM_RESULTS_PER_PAGE = 15;
197 *
198 * app.get('/contacts', (req, res) => {
199 * const query = datastore.createQuery('Contacts')
200 * .limit(NUM_RESULTS_PER_PAGE);
201 *
202 * if (req.query.nextPageCursor) {
203 * query.start(req.query.nextPageCursor);
204 * }
205 *
206 * datastore.runQuery(query, (err, entities, info) => {
207 * if (err) {
208 * // Error handling omitted.
209 * return;
210 * }
211 *
212 * // Respond to the front end with the contacts and the cursoring token
213 * // from the query we just ran.
214 * const frontEndResponse = {
215 * contacts: entities
216 * };
217 *
218 * // Check if more results may exist.
219 * if (info.moreResults !== datastore.NO_MORE_RESULTS) {
220 * frontEndResponse.nextPageCursor = info.endCursor;
221 * }
222 *
223 * res.render('contacts', frontEndResponse);
224 * });
225 * });
226 *
227 * @example <caption>Creating Records</caption>
228 * // New entities can be created and persisted with {@link Datastore#save}.
229 * // The entitiy must have a key to be saved. If you don't specify an
230 * // identifier for the key, one is generated for you.
231 * //
232 * // We will create a key with a `name` identifier, "Google".
233 * //-
234 * const key = datastore.key(['Company', 'Google']);
235 *
236 * const data = {
237 * name: 'Google',
238 * location: 'CA'
239 * };
240 *
241 * datastore.save({
242 * key: key,
243 * data: data
244 * }, (err) => {
245 * if (!err) {
246 * // Record saved successfully.
247 * }
248 * });
249 *
250 * //-
251 * // We can verify the data was saved by using {@link Datastore#get}.
252 * //-
253 * datastore.get(key, (err, entity) => {
254 * // entity = {
255 * // name: 'Google',
256 * // location: 'CA'
257 * // }
258 * });
259 *
260 * //-
261 * // If we want to update this record, we can modify the data object and re-
262 * // save it.
263 * //-
264 * data.symbol = 'GOOG';
265 *
266 * datastore.save({
267 * key: key, // defined above (datastore.key(['Company', 'Google']))
268 * data: data
269 * }, (err, entity) => {
270 * if (!err) {
271 * // Record updated successfully.
272 * }
273 * });
274 *
275 * @example <caption>Deleting Records</caption>
276 * // Entities can be removed from Datastore by passing the entity's key object
277 * // to {@link Datastore#delete}.
278 * //-
279 * const key = datastore.key(['Company', 'Google']);
280 *
281 * datastore.delete(key, (err) => {
282 * if (!err) {
283 * // Record deleted successfully.
284 * }
285 * });
286 *
287 * @example <caption>Transactions</caption>
288 * // Complex logic can be wrapped in a transaction with
289 * // {@link Datastore#transaction}. All queries and updates run within
290 * // the transaction will be applied when the `done` function is called.
291 * //-
292 * const transaction = datastore.transaction();
293 *
294 * transaction.run((err) => {
295 * if (err) {
296 * // Error handling omitted.
297 * }
298 *
299 * const key = datastore.key(['Company', 'Google']);
300 *
301 * transaction.get(key, (err, entity) => {
302 * if (err) {
303 * // Error handling omitted.
304 * }
305 *
306 * entity.symbol = 'GOOG';
307 *
308 * transaction.save(entity);
309 *
310 * transaction.commit((err) => {
311 * if (!err) {
312 * // Transaction committed successfully.
313 * }
314 * });
315 * });
316 * });
317 *
318 * @example <caption>Queries with Ancestors</caption>
319 * const {Datastore} = require('@google-cloud/datastore');
320 * const datastore = new Datastore();
321 *
322 * const customerId1 = 2993844;
323 * const customerId2 = 4993882;
324 * const customerKey1 = datastore.key(['Customer', customerId1]);
325 * const customerKey2 = datastore.key(['Customer', customerId2]);
326 * const cookieKey1 = datastore.key(['Customer', customerId1, 'Cookie',
327 * 'cookie28839']); // child entity const cookieKey2 =
328 * datastore.key(['Customer', customerId1, 'Cookie', 'cookie78984']); // child
329 * entity const cookieKey3 = datastore.key(['Customer', customerId2, 'Cookie',
330 * 'cookie93911']); // child entity
331 *
332 * const entities = [];
333 *
334 * entities.push({
335 * key: customerKey1,
336 * data: {
337 * name: 'Jane Doe',
338 * address: '4848 Liller'
339 * }
340 * });
341 *
342 * entities.push({
343 * key: customerKey2,
344 * data: {
345 * name: 'John Smith',
346 * address: '4848 Pine'
347 * }
348 * });
349 *
350 * entities.push({
351 * key: cookieKey1,
352 * data: {
353 * cookieVal: 'dj83kks88rkld'
354 * }
355 * });
356 *
357 * entities.push({
358 * key: cookieKey2,
359 * data: {
360 * cookieVal: 'sj843ka99s'
361 * }
362 * });
363 *
364 * entities.push({
365 * key: cookieKey3,
366 * data: {
367 * cookieVal: 'otk82k2kw'
368 * }
369 * });
370 *
371 * datastore.upsert(entities);
372 *
373 * const query = datastore.createQuery().hasAncestor(customerKey1);
374 *
375 * datastore.runQuery(query, (err, entities) => {
376 * for (let entity of entities) {
377 * console.log(entity[datastore.KEY]);
378 * }
379 * });
380 *
381 * const query2 = datastore.createQuery().hasAncestor(customerKey2);
382 *
383 * datastore.runQuery(query2, (err, entities) => {
384 * for (let entity of entities) {
385 * console.log(entity[datastore.KEY]);
386 * }
387 * });
388 *
389 * datastore.runQuery(query2, (entities) => {
390 * console.log(entities);
391 * });
392 */
393declare class Datastore extends DatastoreRequest {
394 clients_: Map<string, ClientStub>;
395 namespace?: string;
396 defaultBaseUrl_: string;
397 options: DatastoreOptions;
398 baseUrl_?: string;
399 port_?: number;
400 customEndpoint_?: boolean;
401 auth: GoogleAuth;
402 constructor(options?: DatastoreOptions);
403 export(config: ExportEntitiesConfig): Promise<LongRunningResponse>;
404 export(config: ExportEntitiesConfig, callback: LongRunningCallback): void;
405 getIndexes(options?: GetIndexesOptions): Promise<GetIndexesResponse>;
406 getIndexes(options: GetIndexesOptions, callback: GetIndexesCallback): void;
407 getIndexes(callback: GetIndexesCallback): void;
408 /**
409 * Get all of the indexes in this project as a readable object stream.
410 *
411 * @param {GetIndexesOptions} [options] Configuration object. See
412 * {@link Datastore#getIndexes} for a complete list of options.
413 * @returns {ReadableStream<Index>}
414 */
415 getIndexesStream(options?: GetIndexesOptions): NodeJS.ReadableStream;
416 getProjectId(): Promise<string>;
417 import(config: ImportEntitiesConfig): Promise<LongRunningResponse>;
418 import(config: ImportEntitiesConfig, callback: LongRunningCallback): void;
419 /**
420 * Get a reference to an Index.
421 *
422 * @param {string} id The index name or id.
423 * @returns {Index}
424 */
425 index(id: string): Index;
426 insert(entities: Entities): Promise<InsertResponse>;
427 insert(entities: Entities, callback: InsertCallback): void;
428 save(entities: Entities, gaxOptions?: CallOptions): Promise<SaveResponse>;
429 save(entities: Entities, gaxOptions: CallOptions, callback: SaveCallback): void;
430 save(entities: Entities, callback: SaveCallback): void;
431 update(entities: Entities): Promise<UpdateResponse>;
432 update(entities: Entities, callback: UpdateCallback): void;
433 upsert(entities: Entities): Promise<UpsertResponse>;
434 upsert(entities: Entities, callback: UpsertCallback): void;
435 /**
436 * Helper function to get a Datastore Double object.
437 *
438 * @param {number} value The double value.
439 * @returns {object}
440 *
441 * @example
442 * const {Datastore} = require('@google-cloud/datastore');
443 * const datastore = new Datastore();
444 * const threeDouble = datastore.double(3.0);
445 */
446 static double(value: number): entity.Double;
447 double(value: number): entity.Double;
448 /**
449 * Helper function to check if something is a Datastore Double object.
450 *
451 * @param {*} value
452 * @returns {boolean}
453 *
454 * @example
455 * const {Datastore} = require('@google-cloud/datastore');
456 * const datastore = new Datastore();
457 * datastore.isDouble(0.42); // false
458 * datastore.isDouble(datastore.double(0.42)); // true
459 */
460 static isDouble(value?: {}): boolean;
461 isDouble(value?: {}): boolean;
462 /**
463 * Helper function to get a Datastore Geo Point object.
464 *
465 * @param {object} coordinates Coordinate value.
466 * @param {number} coordinates.latitude Latitudinal value.
467 * @param {number} coordinates.longitude Longitudinal value.
468 * @returns {object}
469 *
470 * @example
471 * const {Datastore} = require('@google-cloud/datastore');
472 * const datastore = new Datastore();
473 * const coordinates = {
474 * latitude: 40.6894,
475 * longitude: -74.0447
476 * };
477 *
478 * const geoPoint = datastore.geoPoint(coordinates);
479 *
480 * //-
481 * // List all companies that are located at 40.123 latitude
482 * // and -74.0447 longitude.
483 * //-
484 * const query = datastore.createQuery('Company');
485 * const companyQuery = query
486 * .filter('geoPoint.latitude', datastore.double(40.123))
487 * .filter('geoPoint.longitude', datastore.double(-74.0447));
488 */
489 static geoPoint(coordinates: entity.Coordinates): entity.GeoPoint;
490 geoPoint(coordinates: entity.Coordinates): entity.GeoPoint;
491 /**
492 * Helper function to check if something is a Datastore Geo Point object.
493 *
494 * @param {*} value
495 * @returns {boolean}
496 *
497 * @example
498 * const {Datastore} = require('@google-cloud/datastore');
499 * const datastore = new Datastore();
500 * const coordinates = {
501 * latitude: 0,
502 * longitude: 0
503 * };
504 *
505 * datastore.isGeoPoint(coordinates); // false
506 * datastore.isGeoPoint(datastore.geoPoint(coordinates)); // true
507 */
508 static isGeoPoint(value?: {}): boolean;
509 isGeoPoint(value?: {}): boolean;
510 /**
511 * Helper function to get a Datastore Integer object.
512 *
513 * This is also useful when using an ID outside the bounds of a JavaScript
514 * Number object.
515 *
516 * @param {number} value The integer value.
517 * @returns {object}
518 *
519 * @example
520 * const {Datastore} = require('@google-cloud/datastore');
521 * const datastore = new Datastore();
522 * const sevenInteger = datastore.int(7);
523 *
524 * //-
525 * // Create an Int to support long Key IDs.
526 * //-
527 * const key = datastore.key([
528 * 'Kind',
529 * datastore.int('100000000000001234')
530 * ]);
531 */
532 static int(value: number | string): entity.Int;
533 int(value: number | string): entity.Int;
534 /**
535 * Helper function to check if something is a Datastore Integer object.
536 *
537 * @param {*} value
538 * @returns {boolean}
539 *
540 * @example
541 * const {Datastore} = require('@google-cloud/datastore');
542 * const datastore = new Datastore();
543 * datastore.isInt(42); // false
544 * datastore.isInt(datastore.int(42)); // true
545 */
546 static isInt(value?: {}): boolean;
547 isInt(value?: {}): boolean;
548 /**
549 * Access the Key from an Entity object.
550 *
551 * @name Datastore.KEY
552 * @type {symbol}
553 */
554 /**
555 * Access the Key from an Entity object.
556 *
557 * @name Datastore#KEY
558 * @type {symbol}
559 */
560 static KEY: typeof entity.KEY_SYMBOL;
561 KEY: typeof entity.KEY_SYMBOL;
562 /**
563 * This is one of three values which may be returned from
564 * {@link Datastore#runQuery}, {@link Transaction#runQuery}, and
565 * {@link Query#run} as `info.moreResults`.
566 *
567 * There *may* be more results after the specified end cursor.
568 *
569 * @type {string}
570 */
571 static MORE_RESULTS_AFTER_CURSOR: string;
572 MORE_RESULTS_AFTER_CURSOR: string;
573 /**
574 * This is one of three values which may be returned from
575 * {@link Datastore#runQuery}, {@link Transaction#runQuery}, and
576 * {@link Query#run} as `info.moreResults`.
577 *
578 * There *may* be more results after the specified limit.
579 *
580 * @type {string}
581 */
582 static MORE_RESULTS_AFTER_LIMIT: string;
583 MORE_RESULTS_AFTER_LIMIT: string;
584 /**
585 * This is one of three values which may be returned from
586 * {@link Datastore#runQuery}, {@link Transaction#runQuery}, and
587 * {@link Query#run} as `info.moreResults`.
588 *
589 * There are no more results left to query for.
590 *
591 * @type {string}
592 */
593 static NO_MORE_RESULTS: string;
594 NO_MORE_RESULTS: string;
595 createQuery(kind?: string): Query;
596 createQuery(kind?: string[]): Query;
597 createQuery(namespace: string, kind: string): Query;
598 createQuery(namespace: string, kind: string[]): Query;
599 key(options: entity.KeyOptions): entity.Key;
600 key(path: PathType[]): entity.Key;
601 key(path: string): entity.Key;
602 /**
603 * Helper function to check if something is a Datastore Key object.
604 *
605 * @param {*} value
606 * @returns {boolean}
607 *
608 * @example
609 * const {Datastore} = require('@google-cloud/datastore');
610 * const datastore = new Datastore();
611 * datastore.isKey({path: ['Company', 123]}); // false
612 * datastore.isKey(datastore.key(['Company', 123])); // true
613 */
614 static isKey(value?: {}): boolean;
615 isKey(value?: {}): boolean;
616 keyToLegacyUrlSafe(key: entity.Key, locationPrefix?: string): Promise<string>;
617 keyToLegacyUrlSafe(key: entity.Key, callback: KeyToLegacyUrlSafeCallback): void;
618 keyToLegacyUrlSafe(key: entity.Key, locationPrefix: string, callback: KeyToLegacyUrlSafeCallback): void;
619 /**
620 * Helper to convert URL safe key string to entity key object
621 *
622 * This is intended to work with the "legacy" representation of a
623 * datastore "Key" used within Google App Engine (a so-called "Reference").
624 *
625 * @param {entity.Key} key Entity key object.
626 * @param {string} locationPrefix Optional .
627 * The location prefix of an App Engine project ID.
628 * Often this value is 's~', but may also be 'e~', or other location prefixes
629 * currently unknown.
630 * @returns {string} Created urlsafe key.
631 *
632 * @example
633 * const {Datastore} = require('@google-cloud/datastore');
634 * const datastore = new Datastore();
635 * const urlSafeKey = 'ag9ncmFzcy1jbHVtcC00NzlyEwsSB0NvbXBhbnkiBkdvb2dsZQw';
636 *
637 * datastore.keyFromLegacyUrlsafe(key);
638 *
639 */
640 keyFromLegacyUrlsafe(key: string): entity.Key;
641 /**
642 * Create a new Transaction object.
643 *
644 * @param {object} [options] Configuration object.
645 * @param {string} [options.id] The ID of a previously run transaction.
646 * @param {boolean} [options.readOnly=false] A read-only transaction cannot
647 * modify entities.
648 * @returns {Transaction}
649 *
650 * @example
651 * const {Datastore} = require('@google-cloud/datastore');
652 * const datastore = new Datastore();
653 * const transaction = datastore.transaction();
654 */
655 transaction(options?: TransactionOptions): Transaction;
656 /**
657 * Determine the appropriate endpoint to use for API requests. If not
658 * explicitly defined, check for the "DATASTORE_EMULATOR_HOST" environment
659 * variable, used to connect to a local Datastore server.
660 *
661 * @private
662 *
663 * @param {string} customApiEndpoint Custom API endpoint.
664 */
665 determineBaseUrl_(customApiEndpoint?: string): void;
666 /**
667 * {@link DatastoreRequest} class.
668 *
669 * @name Datastore.DatastoreRequest
670 * @see DatastoreRequest
671 * @type {constructor}
672 */
673 DatastoreRequest: typeof DatastoreRequest;
674 /**
675 * {@link Query} class.
676 *
677 * @name Datastore.Query
678 * @see Query
679 * @type {constructor}
680 */
681 Query: typeof Query;
682 /**
683 * {@link Transaction} class.
684 *
685 * @name Datastore.Transaction
686 * @see Transaction
687 * @type {constructor}
688 */
689 Transaction: typeof Transaction;
690}
691export { Datastore };
692export interface TransactionOptions {
693 id?: string;
694 readOnly?: boolean;
695}
696export { Index, DatastoreRequest, Query, Transaction };
697export interface DatastoreOptions extends GoogleAuthOptions {
698 namespace?: string;
699 apiEndpoint?: string;
700 sslCreds?: ChannelCredentials;
701}
702export interface KeyToLegacyUrlSafeCallback {
703 (err?: Error | null, urlSafeKey?: string): void;
704}
705declare const v1: any;
706export { v1 };