forked from microsoftgraph/msgraph-sdk-go-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbatch_requests.go
307 lines (257 loc) · 9.07 KB
/
batch_requests.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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
package msgraphgocore
import (
"bytes"
"context"
"encoding/gob"
"encoding/json"
"errors"
nethttplibrary "github.com/microsoft/kiota-http-go"
"net/url"
"reflect"
"strconv"
"strings"
"github.com/google/uuid"
abs "github.com/microsoft/kiota-abstractions-go"
abstractions "github.com/microsoft/kiota-abstractions-go"
"github.com/microsoft/kiota-abstractions-go/serialization"
absser "github.com/microsoft/kiota-abstractions-go/serialization"
)
const BatchRequestErrorRegistryKey = "BATCH_REQUEST_ERROR_REGISTRY_KEY"
const jsonContentType = "application/json"
// RequestHeader is a type alias for http request headers
type RequestHeader map[string]string
// Serialize serializes information the current object
func (br RequestHeader) Serialize(writer serialization.SerializationWriter) error {
return nil
}
// GetFieldDeserializers the deserialization information for the current model
func (br RequestHeader) GetFieldDeserializers() map[string]func(serialization.ParseNode) error {
return make(map[string]func(serialization.ParseNode) error)
}
// RequestBody is a type alias for http request bodies
type RequestBody map[string]interface{}
// Serialize serializes information the current object
func (br RequestBody) Serialize(writer serialization.SerializationWriter) error {
return nil
}
// GetFieldDeserializers the deserialization information for the current model
func (br RequestBody) GetFieldDeserializers() map[string]func(serialization.ParseNode) error {
return make(map[string]func(serialization.ParseNode) error)
}
type batchRequest struct {
requests []BatchItem
adapter abstractions.RequestAdapter
}
// NewBatchRequest creates an instance of BatchRequest
func NewBatchRequest(adapter abstractions.RequestAdapter) BatchRequest {
return &batchRequest{
adapter: adapter,
}
}
// BatchRequest models all the properties of a batch request
type BatchRequest interface {
serialization.Parsable
GetRequests() []BatchItem
SetRequests(requests []BatchItem)
AddBatchRequestStep(reqInfo abstractions.RequestInformation) (BatchItem, error)
Send(ctx context.Context, adapter abstractions.RequestAdapter) (BatchResponse, error)
}
// GetRequests return all the Items in the batch request
func (br *batchRequest) GetRequests() []BatchItem {
return br.requests
}
// SetRequests add a collection of requests to the batch Items
func (br *batchRequest) SetRequests(requests []BatchItem) {
br.requests = requests
}
// Serialize serializes information the current object
func (br *batchRequest) Serialize(writer serialization.SerializationWriter) error {
{
cast := abs.CollectionApply(br.requests, func(v BatchItem) serialization.Parsable {
return v.(serialization.Parsable)
})
err := writer.WriteCollectionOfObjectValues("requests", cast)
if err != nil {
return err
}
}
return nil
}
// GetFieldDeserializers the deserialization information for the current model
func (br *batchRequest) GetFieldDeserializers() map[string]func(serialization.ParseNode) error {
return make(map[string]func(serialization.ParseNode) error)
}
// AddBatchRequestStep converts RequestInformation to a BatchItem and adds it to a BatchRequest
//
// You can add upto 20 BatchItems to a BatchRequest
func (br *batchRequest) AddBatchRequestStep(reqInfo abstractions.RequestInformation) (BatchItem, error) {
return br.addLimitedBatchRequestStep(reqInfo, 19)
}
func (br *batchRequest) addLimitedBatchRequestStep(reqInfo abstractions.RequestInformation, requestLimit int) (BatchItem, error) {
if requestLimit != -1 && len(br.GetRequests()) > requestLimit {
return nil, errors.New("batch items limit exceeded. BatchRequest has a limit of 20 batch items")
}
batchItem, err := br.toBatchItem(reqInfo)
if err != nil {
return nil, err
}
br.SetRequests(append(br.GetRequests(), batchItem))
return batchItem, nil
}
func (br *batchRequest) toBatchItem(requestInfo abstractions.RequestInformation) (BatchItem, error) {
if _, ok := requestInfo.PathParameters["baseurl"]; !ok {
// address issue for request information missing baseUrl
// https://github.com/microsoft/kiota/issues/2061
requestInfo.PathParameters["baseurl"] = br.adapter.GetBaseUrl()
}
uri, err := requestInfo.GetUri()
if err != nil {
return nil, err
}
uriString := nethttplibrary.ReplacePathTokens(uri.String(), ReplacementPairs)
var body map[string]interface{}
if requestInfo.Content != nil {
err = json.Unmarshal(requestInfo.Content, &body)
if err != nil {
return nil, err
}
}
newID := uuid.NewString()
method := requestInfo.Method.String()
request := NewBatchItem()
request.SetId(&newID)
request.SetMethod(&method)
request.SetBody(body)
headers := make(map[string]string)
for _, key := range requestInfo.Headers.ListKeys() {
value := requestInfo.Headers.Get(key)
headers[key] = strings.Join(value, ",")
}
request.SetHeaders(headers)
baseUri, err := getBaseUrl(br.adapter)
if err != nil {
return nil, err
}
var finalUrl = strings.Replace(uriString, baseUri.String(), "", 1)
request.SetUrl(&finalUrl)
return request, nil
}
// Send serializes and sends the batch request to the server
func (br *batchRequest) Send(ctx context.Context, adapter abstractions.RequestAdapter) (BatchResponse, error) {
baseUrl, err := getBaseUrl(adapter)
if err != nil {
return nil, err
}
requestInfo, err := buildRequestInfo(ctx, adapter, br, baseUrl)
if err != nil {
return nil, err
}
return sendBatchRequest(ctx, requestInfo, adapter)
}
func getBaseUrl(adapter abstractions.RequestAdapter) (*url.URL, error) {
return url.Parse(adapter.GetBaseUrl())
}
func buildRequestInfo(ctx context.Context, adapter abstractions.RequestAdapter, body BatchRequest, baseUrl *url.URL) (*abstractions.RequestInformation, error) {
requestInfo := abstractions.NewRequestInformation()
requestInfo.Method = abstractions.POST
requestInfo.UrlTemplate = "{+baseurl}/$batch"
err := requestInfo.SetContentFromParsable(ctx, adapter, "application/json", body)
if err != nil {
return nil, err
}
requestInfo.Headers.Add("Content-Type", "application/json")
return requestInfo, nil
}
func getResponsePrimaryContentType(responseItem BatchItem) string {
header := responseItem.GetHeaders()
if header == nil {
return ""
}
rawType := header["Content-Type"]
splat := strings.Split(rawType, ";")
return strings.ToLower(splat[0])
}
func getRootParseNode(responseItem BatchItem) (absser.ParseNode, error) {
contentType := getResponsePrimaryContentType(responseItem)
if contentType == "" {
return nil, nil
}
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err := enc.Encode(responseItem.GetBody())
if err != nil {
return nil, err
}
return serialization.DefaultParseNodeFactoryInstance.GetRootParseNode(contentType, buf.Bytes())
}
func throwErrors(responseItem BatchItem, typeName string) error {
errorMappings := getErrorMapper(typeName)
if errorMappings == nil {
errorMappings = getErrorMapper(BatchRequestErrorRegistryKey)
}
responseStatus := *responseItem.GetStatus()
statusAsString := strconv.Itoa(int(responseStatus))
var errorCtor absser.ParsableFactory = nil
if len(errorMappings) != 0 {
if responseStatus >= 400 && responseStatus < 500 && errorMappings["4XX"] != nil {
errorCtor = errorMappings["4XX"]
} else if responseStatus >= 500 && responseStatus < 600 && errorMappings["5XX"] != nil {
errorCtor = errorMappings["5XX"]
}
}
if errorCtor == nil {
return &abstractions.ApiError{
Message: "The server returned an unexpected status code and no error factory is registered for this code: " + statusAsString,
}
}
rootNode, err := getRootParseNode(responseItem)
if err != nil {
return err
}
if rootNode == nil {
return &abstractions.ApiError{
Message: "The server returned an unexpected status code with no response body: " + statusAsString,
}
}
errValue, err := rootNode.GetObjectValue(errorCtor)
if err != nil {
return err
}
return errValue.(error)
}
// GetBatchResponseById returns the response of the batch request item with the given id.
func GetBatchResponseById[T serialization.Parsable](resp BatchResponse, itemId string, constructor absser.ParsableFactory) (T, error) {
var res T
item := resp.GetResponseById(itemId)
if *item.GetStatus() >= 400 {
return res, throwErrors(item, reflect.TypeOf(new(T)).Name())
}
jsonStr, err := json.Marshal(item.GetBody())
if err != nil {
return res, err
}
var parseNodeFactory = absser.DefaultParseNodeFactoryInstance
parseNode, err := parseNodeFactory.GetRootParseNode(jsonContentType, jsonStr)
if err != nil {
return res, err
}
result, err := parseNode.GetObjectValue(constructor)
return result.(T), nil
}
func getErrorMapper(key string) abstractions.ErrorMappings {
errorMapperSrc, found := GetErrorFactoryFromRegistry(key)
if found {
return errorMapperSrc
}
return nil
}
func sendBatchRequest(ctx context.Context, requestInfo *abstractions.RequestInformation, adapter abstractions.RequestAdapter) (BatchResponse, error) {
if requestInfo == nil {
return nil, errors.New("requestInfo cannot be nil")
}
response, err := adapter.Send(ctx, requestInfo, CreateBatchResponseDiscriminator, getErrorMapper(BatchRequestErrorRegistryKey))
if err != nil {
return nil, err
}
return response.(BatchResponse), nil
}