I have a Node.js API using Express. It has the folllowing endpoint, that returns comments for a post with given id.
Now, I would like to implement two features:
- pagination via limit and offset
- data filtering (e.g /comments?title=my%20title) would only return comments that have the requested title. For this one, I’m wondering how to create an index that would work with dynamic parameters.
Here is my trial to handle limit and offset according to this post Recommended way of doing a page offset? - #2 by ben.
// GET comments by post
// Comment model
// commentAuthor: ref
// targetPost: ref
// title: string
// content: string
// comments_by_post is an index that has data.targetPost as term and ref as value on the comments collection
router.get('/:id/comments', async (req, res, next) => {
try {
const limit = req.query.limit ? parseInt(req.query.limit, 10) : 0;
const offset = req.query.offset ? parseInt(req.query.offset, 10) : 0;
const { data } = await db.get().query(
Map(
Drop(
Paginate(Match(Index('comments_by_post'), req.params.id), {
size: limit,
}),
offset
),
Lambda((comment) => Get(comment))
)
);
res.send(data);
} catch (e) {
next(e);
}
});
However, I run into the following because I guess Drop expects an Integer as a first parameter, and I’m giving a Page.
Integer expected, Page provided.
How could I refactor my code to implement the following?
Thanks in advance for any help !