Search code examples
graphqlnestjsnestjs-query

Nestjs-query - How to generate the paginated and unpaginated query?


I'm using Nestjs-query.

I have an object type (ex: Todo) which, most of the time, I want to use pagination to fetch the list.

@ObjectType('Todo')
@QueryOptions({ pagingStrategy: PagingStrategies.CURSOR })
export class Todo {
  @IDField(() => ID)
  id!: number;

  @FilterableField({ nullable: true })
  description?: string;
}

It generates the GraphQL query end point:

  todos(
    """Limit or page results."""
    paging: CursorPaging = {first: 10}

    """Specify to filter the records returned."""
    filter: TodoFilter = {}

    """Specify to sort results."""
    sorting: [TodoSort!] = []
  ): TodoConnection!

But on some occasions, I want to fetch the entire list (unpaginated) of TODOs. But paging.first cannot be null or smaller than 1.

Is there a way to fetch the unpaginated list without writing a new query endpoint by hand?


Solution

  • It is possible by adding a new resolver to the module:

    NestjsQueryGraphQLModule.forFeature({
      imports: [TodoModule],
      resolvers: [
        {
          // Assuming Todo is decorated with `@QueryOptions({ pagingStrategy: PagingStrategies.CURSOR })`
          DTOClass: Todo,
          EntityClass: Todo,
          // ...
        },
        {
          DTOClass: Todo,
          EntityClass: Todo,
          pagingStrategy: PagingStrategies.NONE,
          read: {
            // Give a custom name to not conflict with the first resolver.
            many: { name: 'todoUnpaginated' },
          },
          // ...
        },
      ],
    }),
    

    And it generates the schema:

      todos(
        """Limit or page results."""
        paging: CursorPaging = {first: 10}
    
        """Specify to filter the records returned."""
        filter: TodoFilter = {}
    
        """Specify to sort results."""
        sorting: [TodoSort!] = []
      ): TodoConnection!
      todosUnpaginated(
        """Specify to filter the records returned."""
        filter: TodoFilter = {}
    
        """Specify to sort results."""
        sorting: [TodoSort!] = []
      ): [Todo!]!