UNPKG

25 kBTypeScriptView Raw
1/*!
2 * Copyright 2014 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 */
16import { google } from '../protos/protos';
17import { CallOptions } from 'google-gax';
18import { Duplex, Transform } from 'stream';
19export declare const transactionExpiredError = "This transaction has already expired.";
20export interface AbortableDuplex extends Duplex {
21 abort(): void;
22}
23interface TransactionRequestOptions {
24 readOnly?: {};
25 readWrite?: {
26 previousTransaction?: string | Uint8Array | null;
27 };
28}
29import { entity, Entity, EntityProto, Entities } from './entity';
30import { ExplainOptions, Query, QueryProto, RunQueryInfo, RunQueryOptions, RunQueryResponse, RunQueryCallback } from './query';
31import { Datastore, Transaction } from '.';
32import ITimestamp = google.protobuf.ITimestamp;
33import { AggregateQuery } from './aggregate';
34import { RunOptions } from './transaction';
35/**
36 * By default a DatastoreRequest is in the NOT_TRANSACTION state. If the
37 * DatastoreRequest is a Transaction object, then initially it will be in
38 * the NOT_STARTED state, but then the state will become IN_PROGRESS after the
39 * transaction has started.
40 */
41export declare enum TransactionState {
42 NOT_TRANSACTION = 0,
43 NOT_STARTED = 1,
44 IN_PROGRESS = 2,
45 EXPIRED = 3
46}
47/**
48 * Handle logic for Datastore API operations. Handles request logic for
49 * Datastore.
50 *
51 * Creates requests to the Datastore endpoint. Designed to be inherited by
52 * the {@link Datastore} and {@link Transaction} classes.
53 *
54 * @class
55 */
56declare class DatastoreRequest {
57 id: string | undefined | Uint8Array | null;
58 requests_: Entity | {
59 mutations: Array<{}>;
60 };
61 requestCallbacks_: Array<(err: Error | null, resp: Entity | null) => void> | Entity;
62 datastore: Datastore;
63 protected state: TransactionState;
64 [key: string]: Entity;
65 /**
66 * Format a user's input to mutation methods. This will create a deep clone of
67 * the input, as well as allow users to pass an object in the format of an
68 * entity.
69 *
70 * Both of the following formats can be supplied supported:
71 *
72 * datastore.save({
73 * key: datastore.key('Kind'),
74 * data: { foo: 'bar' }
75 * }, (err) => {})
76 *
77 * const entity = { foo: 'bar' }
78 * entity[datastore.KEY] = datastore.key('Kind')
79 * datastore.save(entity, (err) => {})
80 *
81 * @internal
82 *
83 * @see {@link https://github.com/GoogleCloudPlatform/google-cloud-node/issues/1803}
84 *
85 * @param {object} obj The user's input object.
86 */
87 static prepareEntityObject_(obj: Entity): PrepareEntityObjectResponse;
88 /**
89 * Generate IDs without creating entities.
90 *
91 * @param {Key} key The key object to complete.
92 * @param {number|object} options Either the number of IDs to allocate or an
93 * options object for further customization of the request.
94 * @param {number} options.allocations How many IDs to allocate.
95 * @param {object} [options.gaxOptions] Request configuration options, outlined
96 * here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
97 * @param {function} callback The callback function.
98 * @param {?error} callback.err An error returned while making this request
99 * @param {array} callback.keys The generated IDs
100 * @param {object} callback.apiResponse The full API response.
101 *
102 * @example
103 * ```
104 * const incompleteKey = datastore.key(['Company']);
105 *
106 * //-
107 * // The following call will create 100 new IDs from the Company kind, which
108 * // exists under the default namespace.
109 * //-
110 * datastore.allocateIds(incompleteKey, 100, (err, keys) => {});
111 *
112 * //-
113 * // Or, if you're using a transaction object.
114 * //-
115 * const transaction = datastore.transaction();
116 *
117 * transaction.run((err) => {
118 * if (err) {
119 * // Error handling omitted.
120 * }
121 *
122 * transaction.allocateIds(incompleteKey, 100, (err, keys) => {
123 * if (err) {
124 * // Error handling omitted.
125 * }
126 *
127 * transaction.commit((err) => {
128 * if (!err) {
129 * // Transaction committed successfully.
130 * }
131 * });
132 * });
133 * });
134 *
135 * //-
136 * // You may prefer to create IDs from a non-default namespace by providing
137 * an
138 * // incomplete key with a namespace. Similar to the previous example, the
139 * call
140 * // below will create 100 new IDs, but from the Company kind that exists
141 * under
142 * // the "ns-test" namespace.
143 * //-
144 * const incompleteKey = datastore.key({
145 * namespace: 'ns-test',
146 * path: ['Company']
147 * });
148 *
149 * function callback(err, keys, apiResponse) {}
150 *
151 * datastore.allocateIds(incompleteKey, 100, callback);
152 *
153 * //-
154 * // Returns a Promise if callback is omitted.
155 * //-
156 * datastore.allocateIds(incompleteKey, 100).then((data) => {
157 * const keys = data[0];
158 * const apiResponse = data[1];
159 * });
160 * ```
161 */
162 allocateIds(key: entity.Key, options: AllocateIdsOptions | number): Promise<AllocateIdsResponse>;
163 allocateIds(key: entity.Key, options: AllocateIdsOptions | number, callback: AllocateIdsCallback): void;
164 protected checkExpired(): void;
165 /**
166 * Retrieve the entities as a readable object stream.
167 *
168 * @throws {Error} If at least one Key object is not provided.
169 * @throws {Error} If read time and read consistency cannot both be specified.
170 *
171 * @param {Key|Key[]} keys Datastore key object(s).
172 * @param {object} [options] Optional configuration. See {@link Datastore#get}
173 * for a complete list of options.
174 *
175 * @example
176 * ```
177 * const keys = [
178 * datastore.key(['Company', 123]),
179 * datastore.key(['Product', 'Computer'])
180 * ];
181 *
182 * datastore.createReadStream(keys)
183 * .on('error', (err) => {})
184 * .on('data', (entity) => {
185 * // entity is an entity object.
186 * })
187 * .on('end', () => {
188 * // All entities retrieved.
189 * });
190 * ```
191 */
192 createReadStream(keys: Entities, options?: CreateReadStreamOptions): Transform;
193 /**
194 * Delete all entities identified with the specified key(s).
195 *
196 * @param {Key|Key[]} key Datastore key object(s).
197 * @param {object} [gaxOptions] Request configuration options, outlined here:
198 * https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
199 * @param {function} callback The callback function.
200 * @param {?error} callback.err An error returned while making this request
201 * @param {object} callback.apiResponse The full API response.
202 *
203 * @example
204 * ```
205 * const key = datastore.key(['Company', 123]);
206 * datastore.delete(key, (err, apiResp) => {});
207 *
208 * //-
209 * // Or, if you're using a transaction object.
210 * //-
211 * const transaction = datastore.transaction();
212 *
213 * transaction.run((err) => {
214 * if (err) {
215 * // Error handling omitted.
216 * }
217 *
218 * transaction.delete(key);
219 *
220 * transaction.commit((err) => {
221 * if (!err) {
222 * // Transaction committed successfully.
223 * }
224 * });
225 * });
226 *
227 * //-
228 * // Delete multiple entities at once.
229 * //-
230 * datastore.delete([
231 * datastore.key(['Company', 123]),
232 * datastore.key(['Product', 'Computer'])
233 * ], (err, apiResponse) => {});
234 *
235 * //-
236 * // Returns a Promise if callback is omitted.
237 * //-
238 * datastore.delete().then((data) => {
239 * const apiResponse = data[0];
240 * });
241 * ```
242 */
243 delete(keys: Entities, gaxOptions?: CallOptions): Promise<DeleteResponse>;
244 delete(keys: Entities, callback: DeleteCallback): void;
245 delete(keys: Entities, gaxOptions: CallOptions, callback: DeleteCallback): void;
246 /**
247 * Retrieve the entities identified with the specified key(s) in the current
248 * transaction. Get operations require a valid key to retrieve the
249 * key-identified entity from Datastore.
250 *
251 * @throws {Error} If at least one Key object is not provided.
252 *
253 * @param {Key|Key[]} keys Datastore key object(s).
254 * @param {object} [options] Optional configuration.
255 * @param {string} [options.consistency] Specify either `strong` or `eventual`.
256 * If not specified, default values are chosen by Datastore for the
257 * operation. Learn more about strong and eventual consistency
258 * [here](https://cloud.google.com/datastore/docs/articles/balancing-strong-and-eventual-consistency-with-google-cloud-datastore).
259 * @param {object} [options.gaxOptions] Request configuration options, outlined
260 * here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
261 * @param {boolean | IntegerTypeCastOptions} [options.wrapNumbers=false]
262 * Wrap values of integerValue type in {@link Datastore#Int} objects.
263 * If a `boolean`, this will wrap values in {@link Datastore#Int} objects.
264 * If an `object`, this will return a value returned by
265 * `wrapNumbers.integerTypeCastFunction`.
266 * Please see {@link IntegerTypeCastOptions} for options descriptions.
267 * @param {function} callback The callback function.
268 * @param {?error} callback.err An error returned while making this request
269 * @param {object|object[]} callback.entity The entity object(s) which match
270 * the provided keys.
271 *
272 * @example
273 * ```
274 * //-
275 * // Get a single entity.
276 * //-
277 * const key = datastore.key(['Company', 123]);
278 *
279 * datastore.get(key, (err, entity) => {});
280 *
281 * //-
282 * // Or, if you're using a transaction object.
283 * //-
284 * const transaction = datastore.transaction();
285 *
286 * transaction.run((err) => {
287 * if (err) {
288 * // Error handling omitted.
289 * }
290 *
291 * transaction.get(key, (err, entity) => {
292 * if (err) {
293 * // Error handling omitted.
294 * }
295 *
296 * transaction.commit((err) => {
297 * if (!err) {
298 * // Transaction committed successfully.
299 * }
300 * });
301 * });
302 * });
303 *
304 * //-
305 * // Get multiple entities at once with a callback.
306 * //-
307 * const keys = [
308 * datastore.key(['Company', 123]),
309 * datastore.key(['Product', 'Computer'])
310 * ];
311 *
312 * datastore.get(keys, (err, entities) => {});
313 *
314 * //-
315 * // Below is how to update the value of an entity with the help of the
316 * // `save` method.
317 * //-
318 * datastore.get(key, (err, entity) => {
319 * if (err) {
320 * // Error handling omitted.
321 * }
322 *
323 * entity.newValue = true;
324 *
325 * datastore.save({
326 * key: key,
327 * data: entity
328 * }, (err) => {});
329 * });
330 *
331 * //-
332 * // Returns a Promise if callback is omitted.
333 * //-
334 * datastore.get(keys).then((data) => {
335 * const entities = data[0];
336 * });
337 * ```
338 */
339 get(keys: entity.Key | entity.Key[], options?: CreateReadStreamOptions): Promise<GetResponse>;
340 get(keys: entity.Key | entity.Key[], callback: GetCallback): void;
341 get(keys: entity.Key | entity.Key[], options: CreateReadStreamOptions, callback: GetCallback): void;
342 /**
343 * This function saves results from a successful beginTransaction call.
344 *
345 * @param {BeginAsyncResponse} [response] The response from a call to
346 * begin a transaction that completed successfully.
347 *
348 **/
349 protected parseTransactionResponse(resp?: {
350 transaction?: Uint8Array | string | undefined | null;
351 }): void;
352 /**
353 * Datastore allows you to run aggregate queries by supplying aggregate fields
354 * which will determine the type of aggregation that is performed.
355 *
356 * The query is run, and the results are returned in the second argument of
357 * the callback provided.
358 *
359 * @param {AggregateQuery} query AggregateQuery object.
360 * @param {RunQueryOptions} options Optional configuration
361 * @param {function} [callback] The callback function. If omitted, a promise is
362 * returned.
363 *
364 * @throws {Error} If read time and read consistency cannot both be specified.
365 *
366 **/
367 runAggregationQuery(query: AggregateQuery, options?: RunQueryOptions): Promise<RunQueryResponse>;
368 runAggregationQuery(query: AggregateQuery, options: RunQueryOptions, callback: RunAggregationQueryCallback): void;
369 runAggregationQuery(query: AggregateQuery, callback: RunAggregationQueryCallback): void;
370 /**
371 * Datastore allows you to query entities by kind, filter them by property
372 * filters, and sort them by a property name. Projection and pagination are
373 * also supported.
374 *
375 * The query is run, and the results are returned as the second argument to
376 * your callback. A third argument may also exist, which is a query object
377 * that uses the end cursor from the previous query as the starting cursor for
378 * the next query. You can pass that object back to this method to see if more
379 * results exist.
380 * @param {Query} query Query object.
381 * @param {object} [options] Optional configuration.
382 * @param {string} [options.consistency] Specify either `strong` or `eventual`.
383 * If not specified, default values are chosen by Datastore for the
384 * operation. Learn more about strong and eventual consistency
385 * [here](https://cloud.google.com/datastore/docs/articles/balancing-strong-and-eventual-consistency-with-google-cloud-datastore).
386 * @param {object} [options.gaxOptions] Request configuration options, outlined
387 * here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
388 * @param {boolean | IntegerTypeCastOptions} [options.wrapNumbers=false]
389 * Wrap values of integerValue type in {@link Datastore#Int} objects.
390 * If a `boolean`, this will wrap values in {@link Datastore#Int} objects.
391 * If an `object`, this will return a value returned by
392 * `wrapNumbers.integerTypeCastFunction`.
393 * Please see {@link IntegerTypeCastOptions} for options descriptions.
394 * @param {function} [callback] The callback function. If omitted, a readable
395 * stream instance is returned.
396 * @param {?error} callback.err An error returned while making this request
397 * @param {object[]} callback.entities A list of entities.
398 * @param {object} callback.info An object useful for pagination.
399 * @param {?string} callback.info.endCursor Use this in a follow-up query to
400 * begin from where these results ended.
401 * @param {string} callback.info.moreResults Datastore responds with one of:
402 *
403 * - {@link Datastore#MORE_RESULTS_AFTER_LIMIT}: There *may* be more
404 * results after the specified limit.
405 * - {@link Datastore#MORE_RESULTS_AFTER_CURSOR}: There *may* be more
406 * results after the specified end cursor.
407 * - {@link Datastore#NO_MORE_RESULTS}: There are no more results.
408 *
409 * @example
410 * ```
411 * //-
412 * // Where you see `transaction`, assume this is the context that's relevant
413 * to
414 * // your use, whether that be a Datastore or a Transaction object.
415 * //-
416 * const query = datastore.createQuery('Lion');
417 *
418 * datastore.runQuery(query, (err, entities, info) => {
419 * // entities = An array of records.
420 *
421 * // Access the Key object for an entity.
422 * const firstEntityKey = entities[0][datastore.KEY];
423 * });
424 *
425 * //-
426 * // Or, if you're using a transaction object.
427 * //-
428 * const transaction = datastore.transaction();
429 *
430 * transaction.run((err) => {
431 * if (err) {
432 * // Error handling omitted.
433 * }
434 *
435 * transaction.runQuery(query, (err, entities) => {
436 * if (err) {
437 * // Error handling omitted.
438 * }
439 *
440 * transaction.commit((err) => {
441 * if (!err) {
442 * // Transaction committed successfully.
443 * }
444 * });
445 * });
446 * });
447 *
448 * //-
449 * // A keys-only query returns just the keys of the result entities instead
450 * of
451 * // the entities themselves, at lower latency and cost.
452 * //-
453 * const keysOnlyQuery = datastore.createQuery('Lion').select('__key__');
454 *
455 * datastore.runQuery(keysOnlyQuery, (err, entities) => {
456 * const keys = entities.map((entity) => {
457 * return entity[datastore.KEY];
458 * });
459 * });
460 *
461 * //-
462 * // Returns a Promise if callback is omitted.
463 * //-
464 * datastore.runQuery(query).then((data) => {
465 * const entities = data[0];
466 * });
467 * ```
468 */
469 runQuery(query: Query, options?: RunQueryOptions): Promise<RunQueryResponse>;
470 runQuery(query: Query, options: RunQueryOptions, callback: RunQueryCallback): void;
471 runQuery(query: Query, callback: RunQueryCallback): void;
472 /**
473 * Get a list of entities as a readable object stream.
474 *
475 * See {@link Datastore#runQuery} for a list of all available options.
476 *
477 * @param {Query} query Query object.
478 * @param {object} [options] Optional configuration.
479 * @param {object} [options.gaxOptions] Request configuration options, outlined
480 * here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
481 *
482 * @throws {Error} If read time and read consistency cannot both be specified.
483 *
484 * @example
485 * ```
486 * datastore.runQueryStream(query)
487 * .on('error', console.error)
488 * .on('data', (entity) => {
489 * // Access the Key object for this entity.
490 * const key = entity[datastore.KEY];
491 * })
492 * .on('info', (info) => {})
493 * .on('end', () => {
494 * // All entities retrieved.
495 * });
496 *
497 * //-
498 * // If you anticipate many results, you can end a stream early to prevent
499 * // unnecessary processing and API requests.
500 * //-
501 * datastore.runQueryStream(query)
502 * .on('data', (entity) => {
503 * this.end();
504 * });
505 * ```
506 */
507 runQueryStream(query: Query, options?: RunQueryStreamOptions): Transform;
508 private getRequestOptions;
509 private getQueryOptions;
510 /**
511 * Merge the specified object(s). If a key is incomplete, its associated object
512 * is inserted and the original Key object is updated to contain the generated ID.
513 * For example, if you provide an incomplete key (one without an ID),
514 * the request will create a new entity and have its ID automatically assigned.
515 * If you provide a complete key, the entity will be get the data from datastore
516 * and merge with the data specified.
517 * By default, all properties are indexed. To prevent a property from being
518 * included in *all* indexes, you must supply an `excludeFromIndexes` array.
519 *
520 * Maps to {@link Datastore#save}, forcing the method to be `upsert`.
521 *
522 * @param {object|object[]} entities Datastore key object(s).
523 * @param {Key} entities.key Datastore key object.
524 * @param {string[]} [entities.excludeFromIndexes] Exclude properties from
525 * indexing using a simple JSON path notation. See the examples in
526 * {@link Datastore#save} to see how to target properties at different
527 * levels of nesting within your entity.
528 * @param {object} entities.data Data to merge to the same for provided key.
529 * @param {function} callback The callback function.
530 * @param {?error} callback.err An error returned while making this request
531 * @param {object} callback.apiResponse The full API response.
532 */
533 merge(entities: Entities): Promise<CommitResponse>;
534 merge(entities: Entities, callback: SaveCallback): void;
535 /**
536 * @private
537 */
538 prepareGaxRequest_(config: RequestConfig, callback: Function): void;
539 /**
540 * Make a request to the API endpoint. Properties to indicate a transactional
541 * or non-transactional operation are added automatically.
542 *
543 * @param {object} config Configuration object.
544 * @param {object} config.gaxOpts GAX options.
545 * @param {string} config.client The name of the gax client.
546 * @param {function} config.method The gax method to call.
547 * @param {object} config.reqOpts Request options.
548 * @param {function} callback The callback function.
549 *
550 * @private
551 */
552 request_(config: RequestConfig, callback: RequestCallback): void;
553 /**
554 * Make a request as a stream.
555 *
556 * @param {object} config Configuration object.
557 * @param {object} config.gaxOpts GAX options.
558 * @param {string} config.client The name of the gax client.
559 * @param {string} config.method The gax method to call.
560 * @param {object} config.reqOpts Request options.
561 */
562 requestStream_(config: RequestConfig): AbortableDuplex;
563}
564/**
565 * This function gets transaction request options used for defining a
566 * request to create a new transaction on the server.
567 *
568 * @param transaction The transaction for which the request will be made.
569 * @param options Custom options that will be used to create the request.
570 */
571export declare function getTransactionRequest(transaction: Transaction, options: RunOptions): TransactionRequestOptions;
572export interface ConsistencyProtoCode {
573 [key: string]: number;
574}
575export type AllocateIdsResponse = [
576 entity.Key[],
577 google.datastore.v1.IAllocateIdsResponse
578];
579export interface AllocateIdsCallback {
580 (a: Error | null, b: entity.Key[] | null, c: google.datastore.v1.IAllocateIdsResponse): void;
581}
582export interface AllocateIdsOptions {
583 allocations?: number;
584 gaxOptions?: CallOptions;
585}
586export type CreateReadStreamOptions = RunQueryOptions;
587export interface GetCallback {
588 (err?: Error | null, entity?: Entities): void;
589}
590export type GetResponse = [Entities];
591export interface Mutation {
592 [key: string]: EntityProto;
593}
594export interface PrepareEntityObject {
595 [key: string]: google.datastore.v1.Key | undefined;
596}
597export interface PrepareEntityObjectResponse {
598 key?: google.datastore.v1.Key;
599 data?: google.datastore.v1.Entity;
600 method?: string;
601}
602export interface RequestCallback {
603 (a?: Error | null, b?: any): void;
604}
605export interface RunAggregationQueryCallback {
606 (a?: Error | null, b?: any, c?: RunQueryInfo): void;
607}
608export interface RequestConfig {
609 client: string;
610 gaxOpts?: CallOptions;
611 method: string;
612 prepared?: boolean;
613 reqOpts?: RequestOptions;
614}
615export interface SharedQueryOptions {
616 databaseId?: string;
617 explainOptions?: ExplainOptions;
618 projectId?: string;
619 partitionId?: google.datastore.v1.IPartitionId | null;
620 readOptions?: {
621 readConsistency?: number;
622 transaction?: string | Uint8Array | null;
623 readTime?: ITimestamp;
624 newTransaction?: TransactionRequestOptions;
625 consistencyType?: 'readConsistency' | 'transaction' | 'newTransaction' | 'readTime';
626 };
627}
628export interface RequestOptions extends SharedQueryOptions {
629 mutations?: google.datastore.v1.IMutation[];
630 keys?: Entity;
631 transactionOptions?: TransactionRequestOptions | null;
632 transaction?: string | null | Uint8Array;
633 mode?: string;
634 query?: QueryProto;
635 filter?: string;
636 indexId?: string;
637 entityFilter?: google.datastore.admin.v1.IEntityFilter;
638}
639export interface RunAggregationQueryRequest extends SharedQueryOptions {
640 aggregationQuery: AggregationQueryOptions;
641}
642export interface AggregationQueryOptions {
643 nestedQuery: QueryProto;
644 aggregations: Array<any>;
645}
646export type RunQueryStreamOptions = RunQueryOptions;
647export interface CommitCallback {
648 (err?: Error | null, resp?: google.datastore.v1.ICommitResponse): void;
649}
650export type CommitResponse = [google.datastore.v1.ICommitResponse];
651export type SaveCallback = CommitCallback;
652export type SaveResponse = CommitResponse;
653export type DeleteCallback = CommitCallback;
654export type DeleteResponse = CommitResponse;
655/**
656 * Reference to the {@link DatastoreRequest} class.
657 * @name module:@google-cloud/datastore.DatastoreRequest
658 * @see DatastoreRequest
659 */
660export { DatastoreRequest };