npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

paginate-nodejs

v1.0.1

Published

A NPM Package for Cursor-based and Offset-based Pagination.

Downloads

5

Readme

paginate-nodejs

This repository contains two pagination functions for Mongoose models: paginateWithOffset and paginateWithCursor. These functions allow you to easily implement offset-based and cursor-based pagination in your Node.js and Mongoose projects.

Table of Contents

Installation

To use these pagination functions, you can install the paginate-nodejs package as a dependency. Additionally, make sure you have mongoose installed if you haven't already:

  • mongoose: An Object Data Modeling (ODM) library for MongoDB.
npm install paginate-nodejs mongoose 

Usage

Offset Pagination (paginateWithOffset)

Offset pagination is a common pagination method where you specify the page number and the number of results per page. This function provides options to sort the results by a specific field and in a specific direction.

/**
 * Offset pagination function for Mongoose models.
 * @param {mongoose.Model} Model - The Mongoose model to paginate.
 * @param {Object} [filter] - Optional filter conditions.
 * @param {Object} [options] - Pagination options.
 * @param {number} [options.page=1] - The current page number (default is 1).
 * @param {number} [options.perPage=10] - Number of results per page (default is 10).
 * @param {string} [options.sortField] - The field to sort results by.
 * @param {number} [options.sortDirection=1] - Sort direction (1 for ascending, -1 for descending).
 * @returns {Promise<Object>} - An object containing paginated results and metadata.
 */
const { paginateWithOffset } = require('paginate-nodejs');
app.get('/offset-paginate', async (req, res) => {
    try {
        const { page = 1, perPage = 2, sortField = 'age', sortDirection = 1 } = req.query;

        const parsedPage = parseInt(page) || 1;
        const parsedPerPage = parseInt(perPage) || 2;
        const parsedSortDirection = parseInt(sortDirection) || 1;

        const paginationOptions = {
            page: parsedPage,
            perPage: parsedPerPage,
            sortField,
            sortDirection: parsedSortDirection,
        };

        const result = await paginateWithOffset(Model, {}, paginationOptions);

        res.json(result);
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});

/**
 * Offset pagination - cURL
 * http://localhost:3000/offset-paginate?page=1&perPage=10&sortField=age&sortDirection=1
**/

Cursor Pagination (paginateWithCursor)

Cursor pagination is a more efficient method for large datasets. It uses a cursor (usually the ID of the last item from the previous page) to fetch the next set of results.

/**
 * Cursor-based pagination function for Mongoose models.
 * @param {mongoose.Model} model - The Mongoose model to paginate.
 * @param {Object} query - Optional query conditions.
 * @param {string} cursor - The cursor representing the last record in the previous page.
 * @param {number} pageSize - Number of results per page.
 * @returns {Promise<Object>} - An object containing paginated results and metadata.
 */
const { paginateWithCursor } = require('paginate-nodejs');
app.get('/cursor-paginate', async (req, res) => {
    try {
        const { cursor, limit } = req.query;
        const pageSize = parseInt(limit) || 5;

        const query = {};
        const result = await paginateWithCursor(Model, query, cursor, pageSize);
        res.json(result);
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});

/**
 * Cursor pagination - cURL
 * http://localhost:3000/paginate?cursor=`${next}` // replace next with value of the next in response
**/

Contributing

Contributions to paginate-nodejs are welcome! If you'd like to contribute to this project, please follow these steps:

  1. Fork the repository.
  2. Create a new branch for your feature or bug fix: git checkout -b feature/your-feature-name.
  3. Commit your changes: git commit -m "Add your feature or fix".
  4. Push your branch to your fork: git push origin feature/your-feature-name.
  5. Create a pull request on the original repository.

Please follow the Code of Conduct and Contributing Guidelines when contributing.

Buy Me A Coffee