cuttlas
cuttlas

Reputation: 981

Paginating a Root Query field using join-monster library (GraphQL)

I'm struggling to implement Application Layer Paging with the join-monster library following the docs: http://join-monster.readthedocs.io/en/latest/pagination/

All the examples are about paginating a relation from a specific node, but I want to paginate a field from the RootQuery. My RootQuery looks like this:

const RootQuery = new GraphQLObjectType({
  name: "Query",
    articles: {
      type: new GraphQLList(ArticleType),
      args: {},
      resolve(parentValue, args, context, resolveInfo) {
        return joinMonster(
          resolveInfo,
          {},
          sql => {
            return knex.raw(sql).then(result => {
              return result[0];
            });
          },
          { dialect: "mysql" }
        );
      }
    }
  })
});

I want to paginate the articles field, so I've tried to turn it into a connection:

const RootQuery = new GraphQLObjectType({
  name: "Query",
  fields: () => ({
    articles: {
      type: ArticleConnection,
      args: gqlUtils.connectionArgs,
      resolve(parentValue, args, context, resolveInfo) {
        return joinMonster(
          resolveInfo,
          {},
          sql => {
            return knex.raw(sql).then(result => {
              return gqlUtils.connectionFromArray(result[0], args);
            });
          },
          { dialect: "mysql" }
        );
      }
    }
  })
});

but when running a query against it, I get the error

function must return/resolve an array of objects where each object is a row from the result set. Instead got { edges...

And now I'm stuck. Am I approaching it the wrong way? How am I supposed to do it?

Thanks.

Upvotes: 1

Views: 639

Answers (1)

cuttlas
cuttlas

Reputation: 981

That was almost right, the problem is that I was calling "connectionFromArray" before sending the data to joinMonster, and obviously it has to be called afterwards:

const RootQuery = new GraphQLObjectType({
  name: "Query",
  fields: () => ({
    articles: {
      type: ArticleConnection,
      args: connectionArgs,
      resolve(parentValue, args, context, resolveInfo) {
        return joinMonster(
          resolveInfo,
          {},
          sql => {
            return knex.raw(sql).then(result => {
              return result[0];
            });
          },
          { dialect: "mysql" }
        ).then(data => connectionFromArray(data, args));
      }
    }
  })
});

Upvotes: 1

Related Questions