graphql-compose-connection icon indicating copy to clipboard operation
graphql-compose-connection copied to clipboard

Example usage without MongoDB

Open Scimonster opened this issue 6 years ago • 0 comments

I'm using graphql-compose without MongoDB. I have a SQL database, but there's a business logic layer between the DB and GQL. So for practical purposes, my GraphQL layer does not interact with the database, it may as well come from a hardcoded array.

How am i supposed to implement first/after, last/before, limit/skip, and sort like this?

Here is a simplified version of my code:

userType.addResolver(({
  name: 'findMany',
  kind: 'query',
  type: [userType],
  args: {
    first: 'Int',
    after: 'ID',
    last: 'Int',
    before: 'ID',
  },
  resolve: async (rp) => {
    const {source, args, rawQuery} = rp;
    let users = await User.findAll();
    if (rawQuery.id) {
      if (rawQuery.id.$gt) {
        users = users.filter(user => user.id > rawQuery.id.$gt);
      }
      if (rawQuery.id.$lt) {
        users = users.filter(user => user.id < rawQuery.id.$lt);
      }
    }
    if (args.first) {
      users = users.slice(0, args.first);
    }
    if (args.last) {
      users = users.slice(-args.last);
    }
    return users;
  }
}));
userType.addResolver(({
  name: 'count',
  kind: 'query',
  type: 'Int',
  args: {},
  resolve: async ({source, args}) => {
    return (await User.findAll()).length;
  }
}));

composeWithConnection(userType, {
  findResolverName: 'findMany',
  countResolverName: 'count',
  sort: {
    _ID_ASC: {
      value: {_id: 1},
      cursorFields: ['id'],
      beforeCursorQuery: (rawQuery, cursorData, resolveParams) => {
        if (!rawQuery.id) rawQuery.id = {};
        rawQuery.id.$lt = cursorData.id;
      },
      afterCursorQuery: (rawQuery, cursorData, resolveParams) => {
        if (!rawQuery.id) rawQuery.id = {};
        rawQuery.id.$gt = cursorData.id;
      },
    }
  }
});

With this code, it seems to successfully filter, but pageInfo.hasNextPage and hasPreviousPage are always false.

Scimonster avatar Feb 11 '19 13:02 Scimonster