Skip to content

Commit e84582f

Browse files
committed
Add setAncestor
Adds a new setAncestor method for ensuring only one ancestor is set for the query at a time. This will avoid errors that result because of setting multiple ancestors. Also deprecate hasAncestor because it will lead to warnings like this. Add parser logic to use the value provided in setAncestor for query sent to backend.
1 parent bc15f32 commit e84582f

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/entity.ts

+5
Original file line numberDiff line numberDiff line change
@@ -1247,6 +1247,11 @@ export namespace entity {
12471247
? filter
12481248
: new PropertyFilter(filter.name, filter.op, filter.val);
12491249
});
1250+
if (typeof query.ancestor !== 'undefined') {
1251+
filters.push(
1252+
new PropertyFilter('__key__', 'HAS_ANCESTOR', query.ancestor)
1253+
);
1254+
}
12501255
queryProto.filter = Filter.AND(filters).toProto();
12511256
}
12521257

src/query.ts

+25
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ export interface Filter {
7373
* ```
7474
*/
7575
class Query {
76+
ancestor?: Key;
7677
scope?: Datastore | Transaction;
7778
namespace?: string | null;
7879
kinds: string[];
@@ -246,12 +247,36 @@ class Query {
246247
* const query = datastore.createQuery('MyKind');
247248
* const ancestoryQuery = query.hasAncestor(datastore.key(['Parent', 123]));
248249
* ```
250+
*
251+
* @deprecated Use setAncestor().
249252
*/
250253
hasAncestor(key: Key) {
251254
this.filters.push({name: '__key__', op: 'HAS_ANCESTOR', val: key});
252255
return this;
253256
}
254257

258+
/**
259+
* Filter a query by ancestors.
260+
*
261+
* @see {@link https://cloud.google.com/datastore/docs/concepts/queries#datastore-ancestor-query-nodejs| Datastore Ancestor Filters}
262+
*
263+
* @param {Key} key Key object to filter by.
264+
* @returns {Query}
265+
*
266+
* @example
267+
* ```
268+
* const {Datastore} = require('@google-cloud/datastore');
269+
* const datastore = new Datastore();
270+
* const query = datastore.createQuery('MyKind');
271+
* const ancestorQuery = query.setAncestor(datastore.key(['Parent', 123]));
272+
* ```
273+
*
274+
*/
275+
setAncestor(key: Key) {
276+
this.ancestor = key;
277+
return this;
278+
}
279+
255280
/**
256281
* Sort the results by a property name in ascending or descending order. By
257282
* default, an ascending sort order will be used.

0 commit comments

Comments
 (0)