forked from dapr/components-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
graphql.go
194 lines (156 loc) · 5.23 KB
/
graphql.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
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
193
194
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package graphql
import (
"context"
"encoding/json"
"fmt"
"reflect"
"regexp"
"strings"
"time"
graphql "github.com/machinebox/graphql"
"github.com/dapr/components-contrib/bindings"
"github.com/dapr/components-contrib/metadata"
"github.com/dapr/kit/logger"
)
const (
// keys from request's metadata.
commandQuery = "query"
commandMutation = "mutation"
// keys from response's metadata.
respOpKey = "operation"
respStartTimeKey = "start-time"
respEndTimeKey = "end-time"
respDurationKey = "duration"
QueryOperation bindings.OperationKind = "query"
MutationOperation bindings.OperationKind = "mutation"
)
type graphQLMetadata struct {
Endpoint string `mapstructure:"endpoint"`
}
// GraphQL represents GraphQL output bindings.
type GraphQL struct {
client *graphql.Client
header map[string]string
logger logger.Logger
}
// NewGraphQL returns a new GraphQL binding instance.
func NewGraphQL(logger logger.Logger) bindings.OutputBinding {
return &GraphQL{logger: logger}
}
// Init initializes the GraphQL binding.
func (gql *GraphQL) Init(_ context.Context, meta bindings.Metadata) error {
gql.logger.Debug("GraphQL Error: Initializing GraphQL binding")
m := graphQLMetadata{}
err := metadata.DecodeMetadata(meta.Properties, &m)
if err != nil {
return err
}
if m.Endpoint == "" {
return fmt.Errorf("GraphQL Error: Missing GraphQL URL")
}
// Connect to GraphQL Server
client := graphql.NewClient(m.Endpoint)
gql.client = client
gql.header = make(map[string]string)
for k, v := range meta.Properties {
if strings.HasPrefix(k, "header:") {
gql.header[strings.TrimPrefix(k, "header:")] = v
}
}
return nil
}
// Operations returns list of operations supported by GraphQL binding.
func (gql *GraphQL) Operations() []bindings.OperationKind {
return []bindings.OperationKind{
QueryOperation,
MutationOperation,
}
}
// Invoke handles all invoke operations.
func (gql *GraphQL) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*bindings.InvokeResponse, error) {
if req == nil {
return nil, fmt.Errorf("GraphQL Error: Invoke request required")
}
if req.Metadata == nil {
return nil, fmt.Errorf("GraphQL Error: Metadata required")
}
gql.logger.Debugf("operation: %v", req.Operation)
startTime := time.Now()
resp := &bindings.InvokeResponse{
Metadata: map[string]string{
respOpKey: string(req.Operation),
respStartTimeKey: startTime.Format(time.RFC3339Nano),
},
Data: []byte{},
}
var graphqlResponse interface{}
switch req.Operation { //nolint:exhaustive
case QueryOperation:
if err := gql.runRequest(ctx, commandQuery, req, &graphqlResponse); err != nil {
return nil, err
}
case MutationOperation:
if err := gql.runRequest(ctx, commandMutation, req, &graphqlResponse); err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("GraphQL Error: invalid operation type: %s. Expected %s or %s",
req.Operation, QueryOperation, MutationOperation)
}
b, err := json.Marshal(graphqlResponse)
if err != nil {
return nil, fmt.Errorf("GraphQL Error: %w", err)
}
resp.Data = b
endTime := time.Now()
resp.Metadata[respEndTimeKey] = endTime.Format(time.RFC3339Nano)
resp.Metadata[respDurationKey] = endTime.Sub(startTime).String()
return resp, nil
}
func (gql *GraphQL) runRequest(ctx context.Context, requestKey string, req *bindings.InvokeRequest, response interface{}) error {
requestString, ok := req.Metadata[requestKey]
if !ok || requestString == "" {
return fmt.Errorf("GraphQL Error: required %q not set", requestKey)
}
// Check that the command is either a query or mutation based on the first keyword.
requestString = strings.TrimSpace(requestString)
re := regexp.MustCompile(`(?m)` + requestKey + `\b`)
matches := re.FindAllStringIndex(requestString, 1)
if len(matches) != 1 || matches[0][0] != 0 {
return fmt.Errorf("GraphQL Error: command is not a %s", requestKey)
}
request := graphql.NewRequest(requestString)
for headerKey, headerValue := range gql.header {
request.Header.Set(headerKey, headerValue)
}
for k, v := range req.Metadata {
if strings.HasPrefix(k, "header:") {
request.Header.Set(strings.TrimPrefix(k, "header:"), v)
} else if strings.HasPrefix(k, "variable:") {
request.Var(strings.TrimPrefix(k, "variable:"), v)
}
}
if err := gql.client.Run(ctx, request, response); err != nil {
return fmt.Errorf("GraphQL Error: %w", err)
}
return nil
}
// GetComponentMetadata returns the metadata of the component.
func (gql *GraphQL) GetComponentMetadata() map[string]string {
metadataStruct := graphQLMetadata{}
metadataInfo := map[string]string{}
metadata.GetMetadataInfoFromStructType(reflect.TypeOf(metadataStruct), &metadataInfo, metadata.BindingType)
return metadataInfo
}