Skip to content

Commit

Permalink
added support for popping from front and back
Browse files Browse the repository at this point in the history
  • Loading branch information
gilmaimon committed Dec 20, 2018
1 parent 6ee3efe commit 40f0736
Showing 1 changed file with 18 additions and 6 deletions.
24 changes: 18 additions & 6 deletions database-helpers/collections.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,30 +120,37 @@ class CollectionPopRequest {
});
}

__getTop(username, collection_key, popFirstElement, callback) {
__getTop(username, collection_key, popFirstElement, callback) {
this.db.collection('users').aggregate([
{ $match: { username: username } },
{ $project: {
topElements: { $slice: [ "$data." + collection_key, popFirstElement? 0 : -2, 2] },
}},
]).toArray(function(err, res) {
if(err) {
callback(true, null);
callback(true, null, null);
return;
}
// the result will be either: [firstItem, nextItem], [firstItem], [beforeLastItem, lastItem], [lastItem] or [] in case of empty array
// the cases represent diffrent states of the array before popping the value and the code below gets the required value (either
// first item or last item depending on $popFirstElement). also checks if there are more items in the array (returned size is >= 1)
var value = null;
var empty = false;
if(res[0].topElements && res[0].topElements.length > 1) {
if(popFirstElement) value = res[0].topElements[0];
else value = res[0].topElements[1];
} else {
if(res[0].topElements) {
if(res[0].topElements.length == 1) {
value = res[0].topElements[0];
empty = true;
} else {
// There is no such item (probably array is already empty), we consider that case as an error
callback(true, null, null);
return;
}
empty = true;
}

callback(value, empty);
callback(false, value, empty);
})
}

Expand All @@ -154,7 +161,12 @@ class CollectionPopRequest {
var collection_key = this.request.collection_key
var that = this;

this.__getTop(username, collection_key, popFirstElement, function(value, willBeEmpty) {
this.__getTop(username, collection_key, popFirstElement, function(err, value, willBeEmpty) {
if(err) {
callback(true, null);
return;
}

that.__popItem(username, collection_key, popFirstElement, value, willBeEmpty, callback);
});
}
Expand Down

0 comments on commit 40f0736

Please sign in to comment.