Skip to content
This repository has been archived by the owner on Jan 2, 2024. It is now read-only.

Commit

Permalink
Add limit filter
Browse files Browse the repository at this point in the history
  • Loading branch information
henriquecarv committed Nov 26, 2018
1 parent fd4bea8 commit 399d979
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 9 deletions.
26 changes: 17 additions & 9 deletions lib/google-cloud-datastore-database.js
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
Expand All @@ -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;
Expand Down
9 changes: 9 additions & 0 deletions test/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 399d979

Please sign in to comment.