diff --git a/lib/google-cloud-datastore-database.js b/lib/google-cloud-datastore-database.js index adeaff9..ea4a59d 100644 --- a/lib/google-cloud-datastore-database.js +++ b/lib/google-cloud-datastore-database.js @@ -150,13 +150,15 @@ class GoogleCloudDatastore { */ async all(model, filter, options, callback) { const where = filter.where; + const limit = filter.limit; + try { let result; if (where && where.id) { result = await this.findById(model, where.id); - } else if (where) { - const query = this.buildQuery(model, where); + } else if (where || limit) { + const query = this.buildQuery(model, where, limit); const entities = await query.run(); result = this.completeEntities(entities[0]); @@ -175,15 +177,21 @@ class GoogleCloudDatastore { * @param {String} model The model name * @param {Object} where The filter */ - buildQuery(model, where) { - const filters = Object.keys(where).map((key) => ({ - [key]: where[key], - })); - + buildQuery(model, where, limit) { let query = this.db.createQuery(model); - for (let i = 0; i < filters.length; i += 1) { - query = this.addFiltersToQuery(query, filters[i]); + if (where) { + const filters = Object.keys(where).map((key) => ({ + [key]: where[key], + })); + + for (let i = 0; i < filters.length; i += 1) { + query = this.addFiltersToQuery(query, filters[i]); + } + } + + if (limit) { + query = query.limit(limit); } return query; diff --git a/test/model.test.js b/test/model.test.js index 14d5629..45f0b6c 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -87,6 +87,15 @@ describe('Loopback Google Cloud Datastore Connector', () => { }); }); + it('Should get one entity from all using limit filter', (done) => { + Customer.all({limit: 1}, (error, customer) => { + customer.should.have.length(1); + customer.should.containDeep([{id: customer1.id}]); + + done(error, customer); + }); + }); + it('Should find entities by age less than 28', (done) => { Customer.find({where: {age: {lt: 28}}}, (error, customer) => { customer.should.have.length(2);