Skip to content

carlosstrand/graphql-pagination-go

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Documentation Actions Status Coverage Status

graphql-pagination-go

This library makes it easy to create paginated fields for graphql-go. We currently have the following features:

  • Simple Pagination (data & count)
  • Separated data and count resolvers
  • Resolvers are executed only for requested fields
  • Skip and Limit

Example:

  fields := graphql.Fields{
    "languages": pagination.Paginated(&pagination.PaginatedField{
      Name: "Languages",
      Type: graphql.String,
      Args: nil,
      DataResolve: func(p graphql.ResolveParams, page pagination.Page) (i interface{}, e error) {
          return []string{"Go", "Javascript", "Ruby"}, nil
      },
      CountResolve: func(p graphql.ResolveParams, page pagination.Page) (i interface{}, e error) {
          return 3, nil
      },
    }),
  }
  rootQuery := graphql.ObjectConfig{Name: "RootQuery", Fields: fields}
  schemaConfig := graphql.SchemaConfig{Query: graphql.NewObject(rootQuery)}

Now you can query as below:

  query {
    languages(limit: 10, skip: 20) {
      data
      count
    }
  }

Skip and Limit

This library already has the limit and skip arguments ready to be used in a query with the database or external service. See the following example:

  var DataResolver = func(p graphql.ResolveParams, page pagination.Page) (i interface{}, e error) {
      users, err := users.FindMany(db.Filter{
        Limit: page.Limit,
        Skip: page.Skip,
      })
      if err != nil {
        return nil, err
      }
      return users, nil
  }

Resolve only requested fields

In some datasources or databases like MongoDB, calling a count comes at an additional cost and is not always used. Thus, this library takes care of resolvers only of the requested fields (data and / or count).

  query {
    languages {
      count
    }
  }

As you can see in example above, only the CountResolve you be called and the query will not have the cost of calling DataResolve because data was not requested.

Resolve Data and Count at once

If your API or your Database already returns Data and Count, you can use DataAndCountResolver. Example:

  fields := graphql.Fields{
    "languages": pagination.Paginated(&PaginatedField{
        Name: "Languages",
        Type: graphql.String,
        Args: nil,
        DataAndCountResolve: func(p graphql.ResolveParams, page Page) (interface{}, int, error) {
            return []string{"Go", "Javascript", "Ruby", "Elixir"}, 4, nil
        },
    }),
  }