UNPKG

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