Skip to content

Commit

Permalink
Merge pull request #85 from lesterzone/internal-promises
Browse files Browse the repository at this point in the history
Simple way to handle/create required promises internally
  • Loading branch information
niftylettuce authored Sep 29, 2016
2 parents d8e8299 + 8581975 commit 3366694
Showing 1 changed file with 12 additions and 13 deletions.
25 changes: 12 additions & 13 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ function paginate(query, options, callback) {
let leanWithId = options.hasOwnProperty('leanWithId') ? options.leanWithId : true;
let limit = options.hasOwnProperty('limit') ? options.limit : 10;
let page, offset, skip, docsQuery, promises;

if (options.offset) {
offset = options.offset;
skip = offset;
Expand All @@ -39,28 +40,25 @@ function paginate(query, options, callback) {
offset = 0;
skip = offset;
}

if (limit > 0) {
docsQuery = this.find(query)
.select(select)
.sort(sort)
.skip(skip)
.limit(limit)
.lean(lean);

if (populate) {
[].concat(populate).forEach((item) => {
docsQuery.populate(item);
});
[].concat(populate).forEach((item) => docsQuery.populate(item));
}
}
promises = {
docs: (docsQuery) ? docsQuery.exec() : false,
count: this.count(query).exec()
};
promises = Object.keys(promises).map((index) => {
if (promises[index]) {
return promises[index];
}
});

promises = [
docsQuery ? docsQuery.exec() : Promise.resolve({}),
this.count(query).exec()
];

let promise = new Promise((resolve, reject) => {
Promise.all(promises).then((data) => {
let docs = (limit > 0) ? data[0] : [];
Expand All @@ -74,7 +72,7 @@ function paginate(query, options, callback) {
result.docs = result.docs.map((doc) => {
doc.id = String(doc._id);
return doc;
});
});
}
if (offset !== undefined) {
result.offset = offset;
Expand All @@ -94,6 +92,7 @@ function paginate(query, options, callback) {
reject(error);
});
});

return promise;
}

Expand Down

0 comments on commit 3366694

Please sign in to comment.