@graphql-pagination/sql-knex
TypeScript icon, indicating that this package has built-in type declarations

1.5.6 • Public • Published

GraphQL Pagination / SQL Knex

Module provides SQL DataSource for Graphql Pagination based on Knex.js.

Usage

Initialize the SqlKnexDataSource with following config:

const ds = new SqlKnexDataSource({
    tableName: "book",      // Base table name
    idFieldName: "id",      // column used as cursor.
    knex: knex,             // pass your knex instance
    baseQuery: (args) => { return knex("book") },    // [Optional] Customize baseQuery in case of more complicated joins or additional filters.
});

and pass it to dataSourcePager like any other.

const pager = dataSourcePager({
    dataSource: ds,
    typeName: "Book",
});

Example

// BookConnection is generated by dataSourcePager
const typeDefs = gql`
    type Book {
        id: ID!
        title: String
        author: String
        published: DateTime
    }
    type Query {
        booksAsc(first: Int = 10 after: String author: String): BookConnection
        booksDesc(last: Int = 10 before: String author: String): BookConnection
    }
`;


const baseQueryFilter = (args) => {
    return knex(tableName)
        .where(builder => {
            if (args.author) builder.where("author", args.author);
        });
};

const ds = new SqlKnexDataSource({
    tableName: tableName,
    idFieldName: "id",
    knex: knex,
    baseQuery: baseQueryFilter,
});

const pager = new dataSourcePager({
    dataSource: ds,
    typeName: "Book",
});

const resolvers = {
    Query: {
        booksAsc: (_, args) => pager.forwardResolver(args),
        booksDesc: (_, args) => pager.backwardResolver(args),
    },
};


const createApolloServer = () => {
    return new ApolloServer({
        typeDefs: [
            typeDefs,
            pager.typeDefs, // BookConnection, BookEdge, PageInfo typeDefs
            scalarTypeDefs, // for DateTime
        ],
        resolvers: [
            resolvers,
            scalarResolvers, // for DateTime
        ],
    });
};

See fully working example in examples/sql-knex.

Readme

Keywords

Package Sidebar

Install

npm i @graphql-pagination/sql-knex

Weekly Downloads

2

Version

1.5.6

License

MIT

Unpacked Size

25.2 kB

Total Files

15

Last publish

Collaborators

  • lkrzyzanek