-
Notifications
You must be signed in to change notification settings - Fork 12
/
users.go
83 lines (68 loc) · 1.69 KB
/
users.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main
import (
"context"
graphql "github.com/graph-gophers/graphql-go"
"github.com/jinzhu/gorm"
"github.com/pkg/errors"
)
// User is the base user model to be used throughout the app
type User struct {
gorm.Model
Name string
Pets []Pet `gorm:"foreignkey:OwnerID"`
}
func (db *DB) getUserPetIDs(ctx context.Context, userID uint) ([]int, error) {
var ids []int
err := db.DB.Where("owner_id = ?", userID).Find(&[]Pet{}).Pluck("id", &ids).Error
if err != nil {
return nil, err
}
return ids, nil
}
func (db *DB) getUser(ctx context.Context, id uint) (*User, error) {
var user User
err := db.DB.First(&user, id).Error
if err != nil {
return nil, err
}
return &user, nil
}
// GetUserPets gets pets associated with the user
func (db *DB) GetUserPets(ctx context.Context, id uint) ([]Pet, error) {
var u User
u.ID = id
var p []Pet
err := db.DB.Model(&u).Association("Pets").Find(&p).Error
if err != nil {
return nil, err
}
return p, nil
}
// UserResolver contains the database and the user model to resolve against
type UserResolver struct {
db *DB
m User
}
// ID resolves the user ID
func (u *UserResolver) ID(ctx context.Context) *graphql.ID {
return gqlIDP(u.m.ID)
}
// Name resolves the Name field for User, it is all caps to avoid name clashes
func (u *UserResolver) Name(ctx context.Context) *string {
return &u.m.Name
}
// Pets resolves the Pets field for User
func (u *UserResolver) Pets(ctx context.Context) (*[]*PetResolver, error) {
pets, err := u.db.GetUserPets(ctx, u.m.ID)
if err != nil {
return nil, errors.Wrap(err, "Pets")
}
r := make([]*PetResolver, len(pets))
for i := range pets {
r[i] = &PetResolver{
db: u.db,
m: pets[i],
}
}
return &r, nil
}