forked from polytomic/go-marketo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bulk.go
243 lines (215 loc) · 5.67 KB
/
bulk.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
package marketo
import (
"bytes"
"context"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/textproto"
"strings"
)
type ImportObject struct {
create string
status string
failures string
}
var (
Leads = ImportObject{
create: "leads",
status: "leads/batch/%d",
failures: "leads/batch/%d/failures",
}
importObjects = map[string]ImportObject{
"lead": Leads,
}
)
// ImportObjectForAPIName returns the ImportObject given the API name
// of a Marketo object
func ImportObjectForAPIName(apiName string) ImportObject {
if obj, ok := importObjects[apiName]; ok {
return obj
}
return ImportObject{
create: fmt.Sprintf("customobjects/%s/import", apiName),
status: fmt.Sprintf("customobjects/%s/import/%%d/status", apiName),
failures: fmt.Sprintf("customobjects/%s/import/%%d/failures", apiName),
}
}
const (
BatchComplete = "Complete"
BatchQueued = "Queued"
BatchImporting = "Importing"
BatchFailed = "Failed"
)
const (
createImport = "create bulk import"
getImport = "get import status"
getImportFailures = "get import failures"
)
// BatchResult contains the details of a batch, returned by the Create
// & Get functions
type BatchResult struct {
BatchID int `json:"batchId"`
ImportID string `json:"importId"`
Status string `json:"status"`
LeadsProcessed int `json:"numOfLeadsProcessed,omitempty"`
Failures int `json:"numOfRowsFailed"`
Warnings int `json:"numOfRowsWithWarning"`
Message string `json:"message"`
ObjectsProcessed int `json:"numOfObjectsProcessed,omitempty"`
ObjectName string `json:"objectApiName,omitempty"`
Processed int `json:"-"`
}
// ImportAPI provides access to the Marketo import API
type ImportAPI struct {
*Client
}
// NewImportAPI returns a new instance of the import API, configured
// using the provided options
func NewImportAPI(c *Client) *ImportAPI {
return &ImportAPI{c}
}
// Create uploads a new file for importing, returning the new
// asynchronous import
func (i *ImportAPI) Create(ctx context.Context, obj ImportObject, file io.Reader) ([]BatchResult, error) {
buffer := &strings.Builder{}
mpWriter := multipart.NewWriter(buffer)
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition",
fmt.Sprintf(`form-data; name="file"; filename="%s"`, "import.csv"))
fileWriter, err := mpWriter.CreatePart(h)
if err != nil {
return nil, err
}
_, err = io.Copy(fileWriter, file)
if err != nil {
return nil, err
}
mpWriter.Close()
request, err := http.NewRequest(http.MethodPost,
i.url("bulk", "v1", fmt.Sprintf("%s.json?format=csv", obj.create)),
bytes.NewBufferString(buffer.String()),
)
if err != nil {
return nil, err
}
request.Header.Add("Content-Type", mpWriter.FormDataContentType())
resp, err := i.Client.doRequest(request)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, handleError(createImport, resp)
}
response := &Response{}
reader := json.NewDecoder(resp.Body)
err = reader.Decode(response)
if err != nil {
return nil, err
}
if len(response.Errors) > 0 {
return nil, ErrorForReasons(resp.StatusCode, response.Errors...)
}
results := []BatchResult{}
err = json.Unmarshal(response.Result, &results)
if err != nil {
return nil, err
}
return results, nil
}
// Get retrieves an existing import by its batch ID
func (i *ImportAPI) Get(ctx context.Context, obj ImportObject, id int) (*BatchResult, error) {
request, err := http.NewRequest(
http.MethodGet, i.url("bulk", "v1", fmt.Sprintf("%s.json",
fmt.Sprintf(obj.status, id),
)), nil,
)
if err != nil {
return nil, err
}
resp, err := i.Client.doRequest(request)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, handleError(getImport, resp)
}
response := &Response{}
reader := json.NewDecoder(resp.Body)
err = reader.Decode(response)
if err != nil {
return nil, err
}
if len(response.Errors) > 0 {
return nil, ErrorForReasons(resp.StatusCode, response.Errors...)
}
result := []BatchResult{}
err = json.Unmarshal(response.Result, &result)
if err != nil {
return nil, err
}
if len(result) < 1 {
return nil, errors.New("not found")
}
for i, r := range result {
result[i].Processed = r.ObjectsProcessed
if r.LeadsProcessed > 0 {
result[i].Processed = r.LeadsProcessed
}
}
return &result[0], nil
}
// LeadImportFailure contains a single lead record failure, along with
// the reason for failure.
type LeadImportFailure struct {
Reason string
Fields map[string]interface{}
}
// Failures returns the list of failed recrods for an import
func (i *ImportAPI) Failures(ctx context.Context, obj ImportObject, id int) ([]LeadImportFailure, error) {
request, err := http.NewRequest(
http.MethodGet, i.url("bulk", "v1", fmt.Sprintf("%s.json",
fmt.Sprintf(obj.failures, id),
)), nil,
)
if err != nil {
return nil, err
}
resp, err := i.Client.doRequest(request)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
// no errors
return nil, nil
}
if resp.StatusCode != http.StatusOK {
return nil, handleError(getImportFailures, resp)
}
reader := csv.NewReader(resp.Body)
header, err := reader.Read()
if err != nil {
return nil, err
}
failures := []LeadImportFailure{}
record, err := reader.Read()
for err == nil {
failure := LeadImportFailure{
Reason: record[len(header)-1],
Fields: map[string]interface{}{},
}
for i := 0; i < len(header)-1; i++ {
failure.Fields[header[i]] = record[i]
}
failures = append(failures, failure)
record, err = reader.Read()
}
return failures, nil
}