lkrzyzanek / graphql-pagination

GraphQL Cursor & Offset Pagination Library

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

GraphQL Pagination codecov

Library to easily wrap data to GraphQL Pagination.

Implements Relay's GraphQL Cursor Connections Specification and supports Offset Pagination.

Designed in modular and extendable way.

Getting Started

You can use built-in DataSourcePager which provides GraphQL Resolver for your Graph. By implementing / using DataSource you have full control how data are provided to the Pager.

You can use one of these provided:

  1. ArrayDataSource - bundled in @graphql-pagination/core module
  2. OffsetDataSourceWrapper - bundled in @graphql-pagination/core module
  3. SQL Knex - bundled in sql-knex module

Or implement your own by implementing the DataSource interface.

Apollo DataSource integration

The package apollo-datasource provides wrapper which extends Apollo's DataSource class so you can easily construct the pager in same way but using ApolloDataSourcePager class.

See apollo-datasource example.

Example

const typeDefs = gql`
    type Book {
        id: ID!
        title: String
        published: DateTime
    }
    type Query {
        booksAsc(first: Int = 10 after: String): BookConnection
        booksDesc(last: Int = 10 before: String): BookConnection
        booksPublishedAsc(first: Int = 10 after: String): BookConnection
        booksPublishedDesc(last: Int = 10 before: String): BookConnection
    }
`;

const books = [];

const ds = new ArrayDataSource(books);
const pagerById = new DataSourcePager({ dataSource: ds, typeName: "Book" });

const dsPublished = new ArrayDataSource(books, "published");
const pagerPublished = new DataSourcePager({ dataSource: dsPublished, typeName: "Book" });

const resolvers = {
    Query: {
        booksAsc: (_, args) => pagerById.forwardResolver(args),
        booksDesc: (_, args) => pagerById.backwardResolver(args),
        booksPublishedAsc: (_, args) => pagerPublished.forwardResolver(args),
        booksPublishedDesc: (_, args) => pagerPublished.backwardResolver(args),
    },
};

return new ApolloServer({
    typeDefs: [
        typeDefs,
        pagerById.typeDefs, // BookConnection, BookEdge, PageInfo typeDefs
        scalarTypeDefs,     // for DateTime
    ],
    resolvers: [
        resolvers,
        scalarResolvers,     // for DateTime
    ],
});

For more examples go to core package.

About

GraphQL Cursor & Offset Pagination Library

License:MIT License


Languages

Language:TypeScript 98.6%Language:JavaScript 1.4%