-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathgraphql.go
More file actions
192 lines (160 loc) · 4.8 KB
/
graphql.go
File metadata and controls
192 lines (160 loc) · 4.8 KB
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package cmd
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"github.com/timescale/tiger-cli/internal/tiger/config"
)
// We currently use a few GraphQL endpoints as part of the OAuth login flow,
// because they were already available and they accept the OAuth access token
// for authentication (whereas savannah-public only accepts the client
// credentials/API Key).
type GraphQLClient struct {
URL string
}
// GraphQLResponse represents a generic GraphQL response wrapper
type GraphQLResponse[T any] struct {
Data *T `json:"data"`
Errors []GraphQLError `json:"errors,omitempty"`
}
// GraphQLError represents an error returned in a GraphQL response
type GraphQLError struct {
Message string `json:"message"`
}
// GetAllProjectsData represents the data from the getAllProjects query
type GetAllProjectsData struct {
GetAllProjects []Project `json:"getAllProjects"`
}
// Project represents a project from the GraphQL API
type Project struct {
ID string `json:"id"`
Name string `json:"name"`
}
// getUserProjects fetches the list of projects the user has access to
func (c *GraphQLClient) getUserProjects(accessToken string) ([]Project, error) {
query := `
query GetAllProjects {
getAllProjects {
id
name
}
}
`
response, err := makeGraphQLRequest[GetAllProjectsData](c.URL, accessToken, query, nil)
if err != nil {
return nil, err
}
return response.GetAllProjects, nil
}
// GetUserData represents the data from the getUser query
type GetUserData struct {
GetUser User `json:"getUser"`
}
// User represents a user from the GraphQL API
type User struct {
ID string `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
// getUser fetches the current user's information
func (c *GraphQLClient) getUser(accessToken string) (*User, error) {
query := `
query GetUser {
getUser {
id
name
email
}
}
`
response, err := makeGraphQLRequest[GetUserData](c.URL, accessToken, query, nil)
if err != nil {
return nil, err
}
return &response.GetUser, nil
}
// CreatePATRecordData represents the data from the createPATRecord mutation
type CreatePATRecordData struct {
CreatePATRecord PATRecordResponse `json:"createPATRecord"`
}
// PATRecordResponse represents the response from creating a PAT record
type PATRecordResponse struct {
ClientCredentials struct {
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
} `json:"clientCredentials"`
}
// createPATRecord creates a new PAT record for the given project
func (c *GraphQLClient) createPATRecord(accessToken, projectID, patName string) (*PATRecordResponse, error) {
query := `
mutation CreatePATRecord($input: CreatePATRecordInput!) {
createPATRecord(createPATRecordInput: $input) {
clientCredentials {
accessKey
secretKey
}
}
}
`
variables := map[string]any{
"input": map[string]any{
"projectId": projectID,
"name": patName,
},
}
response, err := makeGraphQLRequest[CreatePATRecordData](c.URL, accessToken, query, variables)
if err != nil {
return nil, err
}
return &response.CreatePATRecord, nil
}
// makeGraphQLRequest makes a GraphQL request to the API
func makeGraphQLRequest[T any](queryURL, accessToken, query string, variables map[string]any) (*T, error) {
requestBody := map[string]any{
"query": query,
}
if variables != nil {
requestBody["variables"] = variables
}
jsonBody, err := json.Marshal(requestBody)
if err != nil {
return nil, fmt.Errorf("failed to marshal GraphQL request: %w", err)
}
req, err := http.NewRequest("POST", queryURL, strings.NewReader(string(jsonBody)))
if err != nil {
return nil, fmt.Errorf("failed to create HTTP request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", accessToken))
req.Header.Set("User-Agent", fmt.Sprintf("tiger-cli/%s", config.Version))
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to make GraphQL request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("GraphQL request failed with status %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read GraphQL response: %w", err)
}
var response GraphQLResponse[T]
if err := json.Unmarshal(body, &response); err != nil {
return nil, fmt.Errorf("failed to unmarshal GraphQL response: %w", err)
}
// Check for GraphQL errors
if len(response.Errors) > 0 {
var errorMessages []string
for _, gqlErr := range response.Errors {
errorMessages = append(errorMessages, gqlErr.Message)
}
return nil, fmt.Errorf("GraphQL errors: %s", strings.Join(errorMessages, "; "))
}
if response.Data == nil {
return nil, fmt.Errorf("GraphQL response contains no data")
}
return response.Data, nil
}