-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathgraphql.go
More file actions
54 lines (46 loc) · 1.45 KB
/
graphql.go
File metadata and controls
54 lines (46 loc) · 1.45 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
package executor
import (
"context"
"encoding/json"
"fmt"
"strings"
"yapi.run/cli/internal/domain"
)
// graphqlPayload represents the standard GraphQL JSON envelope
type graphqlPayload struct {
Query string `json:"query"`
Variables map[string]any `json:"variables,omitempty"`
}
// GraphQLTransport returns a transport function for GraphQL requests.
func GraphQLTransport(client HTTPClient) TransportFunc {
httpFn := HTTPTransport(client)
return func(ctx context.Context, req *domain.Request) (*domain.Response, error) {
// Construct the GraphQL payload
payload := graphqlPayload{
Query: req.Metadata["graphql_query"],
}
if vars, ok := req.Metadata["graphql_variables"]; ok && vars != "" {
if err := json.Unmarshal([]byte(vars), &payload.Variables); err != nil {
return nil, fmt.Errorf("failed to unmarshal graphql variables: %w", err)
}
}
// Marshal to JSON
jsonBytes, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("failed to marshal graphql payload: %w", err)
}
// Create a new request for HTTP execution
httpReq := &domain.Request{
URL: req.URL,
Method: "POST",
Headers: req.Headers,
Body: strings.NewReader(string(jsonBytes)),
Metadata: req.Metadata, // Preserve metadata (including timeout)
}
if httpReq.Headers == nil {
httpReq.Headers = make(map[string]string)
}
httpReq.Headers["Content-Type"] = "application/json"
return httpFn(ctx, httpReq)
}
}