-
Notifications
You must be signed in to change notification settings - Fork 8
/
dml.go
345 lines (292 loc) · 9.04 KB
/
dml.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
package salesforce
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"github.com/go-viper/mapstructure/v2"
)
type sObjectCollection struct {
AllOrNone bool `json:"allOrNone"`
Records []map[string]any `json:"records"`
}
func convertToMap(obj any) (map[string]any, error) {
var recordMap map[string]any
if _, ok := obj.(map[string]any); ok {
recordMap = obj.(map[string]any)
} else {
err := mapstructure.Decode(obj, &recordMap)
if err != nil {
return nil, errors.New("issue decoding salesforce object, need a key value pair (custom struct or map)")
}
}
return recordMap, nil
}
func convertToSliceOfMaps(obj any) ([]map[string]any, error) {
var recordMap []map[string]any
if _, ok := obj.(map[string]any); ok {
recordMap = obj.([]map[string]any)
} else {
err := mapstructure.Decode(obj, &recordMap)
if err != nil {
return nil, errors.New("issue decoding salesforce object, need a key value pair (custom struct or map)")
}
}
return recordMap, nil
}
func processSalesforceResponse(resp http.Response) ([]SalesforceResult, error) {
results := []SalesforceResult{}
responseData, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
jsonError := json.Unmarshal(responseData, &results)
if jsonError != nil {
return nil, jsonError
}
return results, nil
}
func doBatchedRequestsForCollection(auth *authentication, method string, url string, batchSize int, recordMap []map[string]any) (SalesforceResults, error) {
var results = []SalesforceResult{}
for len(recordMap) > 0 {
var batch, remaining []map[string]any
if len(recordMap) > batchSize {
batch, remaining = recordMap[:batchSize], recordMap[batchSize:]
} else {
batch = recordMap
}
recordMap = remaining
payload := sObjectCollection{
AllOrNone: false,
Records: batch,
}
body, err := json.Marshal(payload)
if err != nil {
return SalesforceResults{Results: results}, err
}
resp, err := doRequest(auth, requestPayload{
method: method,
uri: url,
content: jsonType,
body: string(body),
})
if err != nil {
return SalesforceResults{Results: results}, err
}
currentResults, err := processSalesforceResponse(*resp)
if err != nil {
return SalesforceResults{Results: results}, err
}
results = append(results, currentResults...)
}
for _, result := range results {
if !result.Success {
return SalesforceResults{Results: results, HasSalesforceErrors: true}, nil
}
}
return SalesforceResults{Results: results}, nil
}
func decodeResponseBody(response *http.Response) (value SalesforceResult, err error) {
defer response.Body.Close()
decoder := json.NewDecoder(response.Body)
err = decoder.Decode(&value)
return value, err
}
func doInsertOne(auth *authentication, sObjectName string, record any) (SalesforceResult, error) {
recordMap, err := convertToMap(record)
if err != nil {
return SalesforceResult{}, err
}
recordMap["attributes"] = map[string]string{"type": sObjectName}
delete(recordMap, "Id")
body, err := json.Marshal(recordMap)
if err != nil {
return SalesforceResult{}, err
}
resp, err := doRequest(auth, requestPayload{
method: http.MethodPost,
uri: "/sobjects/" + sObjectName,
content: jsonType,
body: string(body),
})
if err != nil {
return SalesforceResult{}, err
}
data, err := decodeResponseBody(resp)
if err != nil {
fmt.Println("Error decoding: ", err)
return SalesforceResult{}, err
}
return data, nil
}
func doUpdateOne(auth *authentication, sObjectName string, record any) error {
recordMap, err := convertToMap(record)
if err != nil {
return err
}
recordId, ok := recordMap["Id"].(string)
if !ok || recordId == "" {
return errors.New("salesforce id not found in object data")
}
recordMap["attributes"] = map[string]string{"type": sObjectName}
delete(recordMap, "Id")
body, err := json.Marshal(recordMap)
if err != nil {
return err
}
_, err = doRequest(auth, requestPayload{
method: http.MethodPatch,
uri: "/sobjects/" + sObjectName + "/" + recordId,
content: jsonType,
body: string(body),
})
if err != nil {
return err
}
return nil
}
func doUpsertOne(auth *authentication, sObjectName string, fieldName string, record any) (SalesforceResult, error) {
recordMap, err := convertToMap(record)
if err != nil {
return SalesforceResult{}, err
}
externalIdValue, ok := recordMap[fieldName].(string)
if !ok || externalIdValue == "" {
return SalesforceResult{}, fmt.Errorf("salesforce externalId: %s not found in %s data. make sure to append custom fields with '__c'", fieldName, sObjectName)
}
recordMap["attributes"] = map[string]string{"type": sObjectName}
delete(recordMap, "Id")
delete(recordMap, fieldName)
body, err := json.Marshal(recordMap)
if err != nil {
return SalesforceResult{}, err
}
resp, err := doRequest(auth, requestPayload{
method: http.MethodPatch,
uri: "/sobjects/" + sObjectName + "/" + fieldName + "/" + externalIdValue,
content: jsonType,
body: string(body),
})
if err != nil {
return SalesforceResult{}, err
}
data, err := decodeResponseBody(resp)
if err != nil {
fmt.Println("Error decoding: ", err)
return SalesforceResult{}, err
}
return data, nil
}
func doDeleteOne(auth *authentication, sObjectName string, record any) error {
recordMap, err := convertToMap(record)
if err != nil {
return err
}
recordId, ok := recordMap["Id"].(string)
if !ok || recordId == "" {
return errors.New("salesforce id not found in object data")
}
_, err = doRequest(auth, requestPayload{
method: http.MethodDelete,
uri: "/sobjects/" + sObjectName + "/" + recordId,
content: jsonType,
})
if err != nil {
return err
}
return nil
}
func doInsertCollection(auth *authentication, sObjectName string, records any, batchSize int) (SalesforceResults, error) {
recordMap, err := convertToSliceOfMaps(records)
if err != nil {
return SalesforceResults{}, err
}
for i := range recordMap {
delete(recordMap[i], "Id")
recordMap[i]["attributes"] = map[string]string{"type": sObjectName}
}
return doBatchedRequestsForCollection(auth, http.MethodPost, "/composite/sobjects/", batchSize, recordMap)
}
func doUpdateCollection(auth *authentication, sObjectName string, records any, batchSize int) (SalesforceResults, error) {
recordMap, err := convertToSliceOfMaps(records)
if err != nil {
return SalesforceResults{}, err
}
for i := range recordMap {
recordMap[i]["attributes"] = map[string]string{"type": sObjectName}
recordId, ok := recordMap[i]["Id"].(string)
if !ok || recordId == "" {
return SalesforceResults{}, errors.New("salesforce id not found in object data")
}
}
return doBatchedRequestsForCollection(auth, http.MethodPatch, "/composite/sobjects/", batchSize, recordMap)
}
func doUpsertCollection(auth *authentication, sObjectName string, fieldName string, records any, batchSize int) (SalesforceResults, error) {
recordMap, err := convertToSliceOfMaps(records)
if err != nil {
return SalesforceResults{}, err
}
for i := range recordMap {
recordMap[i]["attributes"] = map[string]string{"type": sObjectName}
externalIdValue, ok := recordMap[i][fieldName].(string)
if !ok || externalIdValue == "" {
return SalesforceResults{}, fmt.Errorf("salesforce externalId: %s not found in %s data. make sure to append custom fields with '__c'", fieldName, sObjectName)
}
}
uri := "/composite/sobjects/" + sObjectName + "/" + fieldName
return doBatchedRequestsForCollection(auth, http.MethodPatch, uri, batchSize, recordMap)
}
func doDeleteCollection(auth *authentication, sObjectName string, records any, batchSize int) (SalesforceResults, error) {
recordMap, err := convertToSliceOfMaps(records)
if err != nil {
return SalesforceResults{}, err
}
// we want to verify that ids are present before we start deleting
batchedIds := []string{}
for len(recordMap) > 0 {
var batch, remaining []map[string]any
if len(recordMap) > batchSize {
batch, remaining = recordMap[:batchSize], recordMap[batchSize:]
} else {
batch = recordMap
}
recordMap = remaining
var ids string
for i := range batch {
batch[i]["attributes"] = map[string]string{"type": sObjectName}
recordId, ok := batch[i]["Id"].(string)
if !ok || recordId == "" {
return SalesforceResults{}, errors.New("salesforce id not found in object data")
}
if i == len(batch)-1 {
ids = ids + recordId
} else {
ids = ids + recordId + ","
}
}
batchedIds = append(batchedIds, ids)
}
var results = []SalesforceResult{}
for i := range batchedIds {
resp, err := doRequest(auth, requestPayload{
method: http.MethodDelete,
uri: "/composite/sobjects/?ids=" + batchedIds[i] + "&allOrNone=false",
content: jsonType,
})
if err != nil {
return SalesforceResults{Results: results}, err
}
currentResults, err := processSalesforceResponse(*resp)
if err != nil {
return SalesforceResults{Results: results}, err
}
results = append(results, currentResults...)
}
for _, result := range results {
if !result.Success {
return SalesforceResults{Results: results, HasSalesforceErrors: true}, nil
}
}
return SalesforceResults{Results: results}, nil
}