@graphql-pagination/sql-knex
v1.5.10
Published
GraphQL Pagination - SQL Knex
Downloads
107
Readme
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.