github.com/jepp2078/gqlgen@v0.7.2/example/dataloader/resolvers.go (about) 1 //go:generate gorunpkg github.com/99designs/gqlgen 2 3 package dataloader 4 5 import ( 6 "context" 7 "fmt" 8 "math/rand" 9 "time" 10 ) 11 12 type Customer struct { 13 ID int `json:"id"` 14 Name string `json:"name"` 15 AddressID int 16 } 17 type Order struct { 18 ID int `json:"id"` 19 Date time.Time `json:"date"` 20 Amount float64 `json:"amount"` 21 } 22 23 type Resolver struct{} 24 25 func (r *Resolver) Customer() CustomerResolver { 26 return &customerResolver{r} 27 } 28 29 func (r *Resolver) Order() OrderResolver { 30 return &orderResolver{r} 31 } 32 33 func (r *Resolver) Query() QueryResolver { 34 return &queryResolver{r} 35 } 36 37 type customerResolver struct{ *Resolver } 38 39 func (r *customerResolver) Address(ctx context.Context, obj *Customer) (*Address, error) { 40 return ctxLoaders(ctx).addressByID.Load(obj.AddressID) 41 } 42 43 func (r *customerResolver) Orders(ctx context.Context, obj *Customer) ([]Order, error) { 44 return ctxLoaders(ctx).ordersByCustomer.Load(obj.ID) 45 } 46 47 type orderResolver struct{ *Resolver } 48 49 func (r *orderResolver) Items(ctx context.Context, obj *Order) ([]Item, error) { 50 return ctxLoaders(ctx).itemsByOrder.Load(obj.ID) 51 } 52 53 type queryResolver struct{ *Resolver } 54 55 func (r *queryResolver) Customers(ctx context.Context) ([]Customer, error) { 56 fmt.Println("SELECT * FROM customer") 57 58 time.Sleep(5 * time.Millisecond) 59 60 return []Customer{ 61 {ID: 1, Name: "Bob", AddressID: 1}, 62 {ID: 2, Name: "Alice", AddressID: 3}, 63 {ID: 3, Name: "Eve", AddressID: 4}, 64 }, nil 65 } 66 67 // this method is here to test code generation of nested arrays 68 func (r *queryResolver) Torture1d(ctx context.Context, customerIds []int) ([]Customer, error) { 69 result := make([]Customer, len(customerIds)) 70 for i, id := range customerIds { 71 result[i] = Customer{ID: id, Name: fmt.Sprintf("%d", i), AddressID: rand.Int() % 10} 72 } 73 return result, nil 74 } 75 76 // this method is here to test code generation of nested arrays 77 func (r *queryResolver) Torture2d(ctx context.Context, customerIds [][]int) ([][]Customer, error) { 78 result := make([][]Customer, len(customerIds)) 79 for i := range customerIds { 80 inner := make([]Customer, len(customerIds[i])) 81 for j := range customerIds[i] { 82 inner[j] = Customer{ID: customerIds[i][j], Name: fmt.Sprintf("%d %d", i, j), AddressID: rand.Int() % 10} 83 } 84 result[i] = inner 85 } 86 return result, nil 87 }