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

@pocket-tools/apollo-cursor-pagination

v1.0.3

Published

Relay's Connection implementation for Apollo Server GraphQL library with primary key support for cursor generation.

Downloads

663

Readme

Apollo Cursor Pagination

Implementation of Relay's Connection specs for Apollo Server. Allows your Apollo Server to do cursor-based pagination. It can connect to any ORM, but only the connection with Knex.js is implemented currently. Added primary key support.

Forked from: FleekHQ/apollo-cursor-pagination

Installation

npm install @pocket-tools/apollo-cursor-pagination

Usage

Using an existing connector

Use the paginate function of the connector in your GraphQL resolver.

paginate receives the following arguments:

1- nodesAccessor: An object that can be queried or accessed to obtain a reduced result set.

2- args: GraphQL args for your connection. Can have the following fields: first, last, before, after.

3- orderArgs: If using a connector with stable cursor, you must indicate to paginate how are you sorting your query. Must contain orderColumn (which attribute you are ordering by) and ascOrDesc (which can be asc or desc). Note: apollo-cursor-pagination does not sort your query, you must do it yourself before calling paginate.

For example with the knex connector:

// cats-connection.js
import { knexPaginator as paginate } from 'apollo-cursor-pagination';
import knex from '../../../db'; // Or instantiate a connection here

export default async (_, args) => {
  // orderBy must be the column to sort with or an array of columns for ordering by multiple fields
  // orderDirection must be 'asc' or 'desc', or an array of those values if ordering by multiples
  const {
    first, last, before, after, orderBy, orderDirection,
  } = args;

  const baseQuery = knex('cats');

  const result = await paginate(baseQuery, {first, last, before, after, orderBy, orderDirection});
  /* result will contain:
  * edges
  * totalCount
  * pageInfo { hasPreviousPage, hasNextPage, }
  */
  return result;
};

Formatting Column Names

If you are using something like Objection and have mapped the column names to something like snakeCase instead of camel_case, you'll want to use the formatColumnFn option to make sure you're ordering by and building cursors from the correct column name:

const result = await paginate(
  baseQuery,
  { first, last, before, after, orderBy, orderDirection },
  {
    formatColumnFn: (column) => {
      // Logic to transform your column name goes here...
      return column
    }
  }
);

Important note: Make sure you pass the un-formatted version as your orderBy argument. It helps to create a wrapper around the paginate() function that enforces this. For example, if the formatted database column name is "created_at" and the column name on the model is "createdAt," you would pass "createdAt" as the orderBy argument.

const result = await paginate(
  baseQuery,
  { first, last, before, after, orderBy, orderDirection },
  {
    formatColumnFn: (column) => {
      if (Model.columnNameMappers && Model.columnNameMappers.format) {
        const result = Model.columnNameMappers.format({ [column]: true })
        return Object.keys(result)[0]
      } else {
        return column
      }
    }
  }
);

Customizing Edges

If you have additional metadata you would like to pass along with each edge, as is allowed by the Relay specification, you may do so using the modifyEdgeFn option:

const result = await paginate(
  baseQuery,
  { first, last, before, after, orderBy, orderDirection },
  {
    modifyEdgeFn: (edge) => ({
      ...edge,
      custom: 'foo',
    })
  }
);

Creating your own connector

Only Knex.js is implemented for now. If you want to connect to a different ORM, you must make your own connector.

To create your own connector:

1- Import apolloCursorPaginationBuilder from src/builder/index.js

2- Call apolloCursorPaginationBuilder with the specified params. It will generate a paginate function that you can export to use in your resolvers.

You can base off from src/orm-connectors/knex/custom-pagination.js.

Contributing

Pull requests are welcome, specially to implement new connectors for different ORMs / Query builders.

When submitting a pull request, please include tests for the code you are submitting, and check that you did not break any working test.

Testing and publishing changes

1- Code your changes

2- Run yarn build. This will generate a dist folder with the distributable files

3- cd into the test app and run yarn install and then yarn test. Check that all tests pass.

4- Send the PR. When accepted, the maintainer will publish a new version to npm using the new dist folder.

Note to maintainer

Do not publish using yarn, as it doesn't publishes all dependencies. Use npm publish.

Running the test suite

1- npm link

2- cd tests/test-app

3- npm link @pocket-tools/apollo-cursor-pagination

2- npm install

3- npm test