Search code examples
sequelize.jsgraphqlgraphql-js

How do I define pagination parameters in my schema?


I am trying to create the ability to paginate through my data, but I'm not sure where I need to place the pagination variables.

Here is what I have in my schema:

const Query = new GraphQLObjectType({
  name: 'Query',
  description: 'This is a root Query',
  fields: () => {
    return {
      allPosts: {
        type: new GraphQLList(Post),
        args: {
          offset: {
            type: GraphQLInt
          },
          first: {
            type: GraphQLInt
          }
        },
        resolve(root, args) {
          return Db.models.post.findAll({where: args});
        }
      }
    };
  }
});

In my args, I've created the variables offset and first to be able to use them. Inside in my graphiQL interface I can do this:

{
    allPosts() {
    id
    }
}

And it correctly retrieves all my posts. However if I try to do this:

{
    allPosts(offset:10, first: 10) {
    id
    }
}

"message": "Unknown column 'post.offset' in 'where clause'",


Solution

  • In Sequelize, offset is a separate option from where. Sequelize also doesn't have a first option, but it does have a limit. You can do something like:

    resolve(root, { offset, first: limit }) {
      return Db.models.post.findAll({offset, limit});
    }
    

    You can check out the docs here to see all the options supported by findAll.