-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget.go
115 lines (95 loc) · 2.35 KB
/
get.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
104
105
106
107
108
109
110
111
112
113
114
115
package eywa
import (
"context"
"encoding/json"
"errors"
"fmt"
)
func Get[M Model, MP ModelPtr[M]]() GetQueryBuilder[M] {
return GetQueryBuilder[M]{
QuerySkeleton: QuerySkeleton[M]{
ModelName: (*new(M)).ModelName(),
// fields: append(fields, field),
},
}
}
type GetQueryBuilder[M Model] struct {
QuerySkeleton[M]
}
func (sq GetQueryBuilder[M]) DistinctOn(f FieldName[M]) GetQueryBuilder[M] {
sq.distinctOn = &distinctOn[M]{f}
return sq
}
func (sq GetQueryBuilder[M]) Offset(n int) GetQueryBuilder[M] {
sq.offset = (*offset)(&n)
return sq
}
func (sq GetQueryBuilder[M]) Limit(n int) GetQueryBuilder[M] {
sq.limit = (*limit)(&n)
return sq
}
func (sq GetQueryBuilder[M]) OrderBy(o ...OrderByExpr) GetQueryBuilder[M] {
orderByArr := orderBy(o)
sq.orderBy = &orderByArr
return sq
}
func (sq GetQueryBuilder[M]) Where(w *WhereExpr) GetQueryBuilder[M] {
sq.where = &where{w}
return sq
}
func (sq GetQueryBuilder[M]) MarshalGQL() string {
return sq.QuerySkeleton.MarshalGQL()
}
func (sq GetQueryBuilder[M]) Select(field FieldName[M], fields ...FieldName[M]) GetQuery[M] {
return GetQuery[M]{
sq: &sq,
fields: append(fields, field),
}
}
type GetQuery[M Model] struct {
sq *GetQueryBuilder[M]
fields []FieldName[M]
}
func (sq GetQuery[M]) MarshalGQL() string {
return fmt.Sprintf(
"%s {\n%s\n}",
sq.sq.MarshalGQL(),
FieldNameArray[M](sq.fields).MarshalGQL(),
)
}
func (sq GetQuery[M]) Query() string {
return fmt.Sprintf(
"query get_%s {\n%s\n}",
sq.sq.ModelName,
sq.MarshalGQL(),
)
}
func (sq GetQuery[M]) Variables() map[string]interface{} {
return nil
}
func (sq GetQuery[M]) Exec(client *Client) ([]M, error) {
return sq.ExecWithContext(context.Background(), client)
}
func (sq GetQuery[M]) ExecWithContext(ctx context.Context, client *Client) ([]M, error) {
respBytes, err := client.Do(ctx, sq)
if err != nil {
return nil, err
}
type graphqlResponse struct {
Data map[string][]M `json:"data"`
Errors []GraphQLError `json:"errors"`
}
respObj := graphqlResponse{}
err = json.NewDecoder(respBytes).Decode(&respObj)
if err != nil {
return nil, err
}
if len(respObj.Errors) > 0 {
gqlErrs := make([]error, 0, len(respObj.Errors))
for _, e := range respObj.Errors {
gqlErrs = append(gqlErrs, errors.New(e.Message))
}
return nil, errors.Join(gqlErrs...)
}
return respObj.Data[sq.sq.ModelName], nil
}