Skip to content
This repository has been archived by the owner on Sep 21, 2022. It is now read-only.

Return totalCount = 0 when no documents returned #33

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions lib/graphql/getPaginatedResponseFromAggregate.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@ async function getPaginatedResponseFromAggregate(collection, pipeline, args, {
// eslint-disable-next-line prefer-destructuring
totalCount = nodes[0].totalCount;
}
} else if (includeTotalCount) {
// if includeTotalCount was requested but we're returning 0 nodes, set it to 0
totalCount = 0;
}

return { pipeline, nodes, pageInfo, totalCount };
Expand Down
26 changes: 26 additions & 0 deletions lib/graphql/getPaginatedResponseFromAggregate.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,29 @@ test("includes sort param in pipeline and returns correct result", async () => {
pageInfo: { endCursor: "123end", hasNextPage: false, hasPreviousPage: null, startCursor: "123start" }
});
});

test("returns totalCount == 0 when there are no documents", async () => {
const nodes = [];
mockCollection.aggregate.toArray.mockReturnValueOnce(nodes);
const result = await getPaginatedResponseFromAggregate(mockCollection, mockPipeline, mockArgs);
expect(result).toEqual({
pipeline: expect.arrayContaining([
{
"$someOperator": "someParameter"
},
{
"$addFields": {
totalCount: {
"$sum": 1
}
}
},
{
"$limit": 20
}
]),
nodes,
pageInfo: { hasNextPage: false, hasPreviousPage: null },
totalCount: 0
});
});