forked from 99designs/gqlgen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.go
103 lines (88 loc) · 1.78 KB
/
model.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package starwars
import (
"context"
"encoding/base64"
"fmt"
"strconv"
"strings"
"time"
)
type CharacterFields struct {
ID string
Name string
FriendIds []string
AppearsIn []Episode
}
type Human struct {
CharacterFields
StarshipIds []string
heightMeters float64
Mass float64
}
func (h *Human) Height(unit LengthUnit) float64 {
switch unit {
case "METER", "":
return h.heightMeters
case "FOOT":
return h.heightMeters * 3.28084
default:
panic("invalid unit")
}
}
func (Human) IsCharacter() {}
func (Human) IsSearchResult() {}
type Review struct {
Stars int
Commentary *string
Time time.Time
}
type Droid struct {
CharacterFields
PrimaryFunction string
}
func (Droid) IsCharacter() {}
func (Droid) IsSearchResult() {}
func (r *Resolver) resolveFriendConnection(ctx context.Context, ids []string, first *int, after *string) (FriendsConnection, error) {
from := 0
if after != nil {
b, err := base64.StdEncoding.DecodeString(*after)
if err != nil {
return FriendsConnection{}, err
}
i, err := strconv.Atoi(strings.TrimPrefix(string(b), "cursor"))
if err != nil {
return FriendsConnection{}, err
}
from = i
}
to := len(ids)
if first != nil {
to = from + *first
if to > len(ids) {
to = len(ids)
}
}
return FriendsConnection{
ids: ids,
from: from,
to: to,
}, nil
}
type FriendsConnection struct {
ids []string
from int
to int
}
func (f *FriendsConnection) TotalCount() int {
return len(f.ids)
}
func (f *FriendsConnection) PageInfo() PageInfo {
return PageInfo{
StartCursor: encodeCursor(f.from),
EndCursor: encodeCursor(f.to - 1),
HasNextPage: f.to < len(f.ids),
}
}
func encodeCursor(i int) string {
return base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("cursor%d", i+1)))
}