UNPKG

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