github.com/jepp2078/gqlgen@v0.7.2/example/starwars/model.go (about) 1 package starwars 2 3 import ( 4 "context" 5 "encoding/base64" 6 "fmt" 7 "strconv" 8 "strings" 9 "time" 10 ) 11 12 type CharacterFields struct { 13 ID string 14 Name string 15 FriendIds []string 16 AppearsIn []Episode 17 } 18 19 type Human struct { 20 CharacterFields 21 StarshipIds []string 22 heightMeters float64 23 Mass float64 24 } 25 26 func (h *Human) Height(unit LengthUnit) float64 { 27 switch unit { 28 case "METER", "": 29 return h.heightMeters 30 case "FOOT": 31 return h.heightMeters * 3.28084 32 default: 33 panic("invalid unit") 34 } 35 } 36 37 func (Human) IsCharacter() {} 38 func (Human) IsSearchResult() {} 39 40 type Review struct { 41 Stars int 42 Commentary *string 43 Time time.Time 44 } 45 46 type Droid struct { 47 CharacterFields 48 PrimaryFunction string 49 } 50 51 func (Droid) IsCharacter() {} 52 func (Droid) IsSearchResult() {} 53 54 func (r *Resolver) resolveFriendConnection(ctx context.Context, ids []string, first *int, after *string) (FriendsConnection, error) { 55 from := 0 56 if after != nil { 57 b, err := base64.StdEncoding.DecodeString(*after) 58 if err != nil { 59 return FriendsConnection{}, err 60 } 61 i, err := strconv.Atoi(strings.TrimPrefix(string(b), "cursor")) 62 if err != nil { 63 return FriendsConnection{}, err 64 } 65 from = i 66 } 67 68 to := len(ids) 69 if first != nil { 70 to = from + *first 71 if to > len(ids) { 72 to = len(ids) 73 } 74 } 75 76 return FriendsConnection{ 77 ids: ids, 78 from: from, 79 to: to, 80 }, nil 81 } 82 83 type FriendsConnection struct { 84 ids []string 85 from int 86 to int 87 } 88 89 func (f *FriendsConnection) TotalCount() int { 90 return len(f.ids) 91 } 92 93 func (f *FriendsConnection) PageInfo() PageInfo { 94 return PageInfo{ 95 StartCursor: encodeCursor(f.from), 96 EndCursor: encodeCursor(f.to - 1), 97 HasNextPage: f.to < len(f.ids), 98 } 99 } 100 101 func encodeCursor(i int) string { 102 return base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("cursor%d", i+1))) 103 }