vektah / dataloaden

go generate based DataLoader
MIT License
530 stars 79 forks source link

[Question] How to specify first, last, after, before etc with dataloader #44

Open touyu opened 4 years ago

touyu commented 4 years ago

For example, if you request with GitHub GraphQL API with the following query, the result will be returned considering first and after.

{
  viewer {
    repositories(first: 30) {
      nodes {
        issues(first: 30, after: "Y3Vyc29yOnYyOpHOAp96sw==") {
          nodes {
            title
          }
        }
      }
    }
  }
}

Probably, if I implement something similar api with gqlgen, I should use dataloader for issues. However I can only pass keys to dataloader. How should I pass first, after, etc. information?

calentang commented 4 years ago

i have the same problem,are you resolved it?

touyu commented 4 years ago

I came up with one solution.

Generate code

$ go run github.com/vektah/dataloaden IssueConnectionLoader Param *model_path/model.IssueConnection
type Param struct {
  Key uint
  First *int
  After *stirng
}

Impl Dataloader

Loader := IssueConnectionLoader{
    maxBatch: 100,
    wait:     1 * time.Millisecond,
    fetch: func(ids []Param) ([]*model.IssueConnection, []error) {
              // You can use `first` or `last` param etc...
        },
 }

Impl Resolver

func (r *repositoryResolver) IssueConnection(ctx context.Context, obj *model.Repository, first *int) (*model.IssueConnection, error) {
    param := dataloader.Param{
        Key:   obj.id,
        First: first,
    }
    return dataloader.For(ctx).Loader.Load(param)
}