I am trying to use a PostFetch hook to filter certain results from my collection. I have a set of dates that I am trying to filter. I only want the response to be those dates that are today or in the future. I can determine which are which in my logs using my code but no matter what I do I can't seem to get the code right to filter out those dates that have passed. I currently have it set up to just pass all, how can I get this filtering to work? Any help would be appreciated.
function onPostFetch(request, response, modules)
{
var moment = modules.moment();
var logger = modules.logger;
var today= new Date();
for (var i =0; i<60; i++)
{
var eventDate= response.body[i].date;
if (modules.moment(eventDate).isBefore(today))
{
response.continue();
logger.info("Event Has Passed")
}
else
{
logger.info("Event is Upcoming")
response.continue();
}
}
}
One problem is calling response.continue within your for loop. Response.continue returns the response and halts further processing, so on the first pass through the loop, you are returning without processing the other items.
It gets tricky trying to remove array items within a loop, because when you remove an item from an array, the array gets reindexed. There are two approaches to accomplish what you are after:
Create an array to hold the elements that you want to eventually return, and then replace response.body with this new array
var eventDate = "";
var filteredResults = [];
for (var i = 0; i<response.body.length;i++) {
eventDate= response.body[i].date;
if (modules.moment(eventDate).isBefore(today) {
filteredResults.push(response.body[i];
}
}
response.body = filteredResults;
response.continue();
Splice the array and rebase your indexing
var eventDate = "";
for (i = 0; i < response.body.length; i++) {
eventDate = response.body[i].date;
if (!modules.moment(eventDate).isBefore(today)) {
response.body.splice(i, 1);
i--; // decrement
}
}
response.continue();
Iterate through the loop in reverse
var eventDate = "";
for (i = response.body.length; i >= 0; i--) {
eventDate = response.body[i].date;
if (!modules.moment(eventDate).isBefore(today)) {
response.body.splice(i, 1);
}
}
response.continue();