Skip to content

Commit

Permalink
Fix import users job (#139)
Browse files Browse the repository at this point in the history
  • Loading branch information
sergiught authored Dec 19, 2022
1 parent 88933e1 commit 43d9898
Showing 1 changed file with 48 additions and 17 deletions.
65 changes: 48 additions & 17 deletions management/job.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"encoding/json"
"mime/multipart"
"net/http"
"net/textproto"
"strconv"
"time"
Expand Down Expand Up @@ -97,35 +98,65 @@ func (m *JobManager) ImportUsers(j *Job, opts ...RequestOption) error {
var payload bytes.Buffer
mp := multipart.NewWriter(&payload)

if j.ConnectionID != nil {
mp.WriteField("connection_id", *j.ConnectionID)
if err := mp.WriteField("connection_id", j.GetConnectionID()); err != nil {
return err
}
if j.Upsert != nil {
mp.WriteField("upsert", strconv.FormatBool(*j.Upsert))
if err := mp.WriteField("upsert", strconv.FormatBool(j.GetUpsert())); err != nil {
return err
}
if j.ExternalID != nil {
mp.WriteField("external_id", *j.ExternalID)
if err := mp.WriteField("external_id", j.GetExternalID()); err != nil {
return err
}
if j.SendCompletionEmail != nil {
mp.WriteField("send_completion_email", strconv.FormatBool(*j.SendCompletionEmail))
if err := mp.WriteField("send_completion_email", strconv.FormatBool(j.GetSendCompletionEmail())); err != nil {
return err
}

if j.Users != nil {
b, err := json.Marshal(j.Users)
usersJSON, err := json.Marshal(j.Users)
if err != nil {
return err
}
h := textproto.MIMEHeader{}
h.Set("Content-Disposition", `form-data; name="users"; filename="users.json"`)
h.Set("Content-Type", "application/json")
w, err := mp.CreatePart(h)

header := textproto.MIMEHeader{}
header.Set("Content-Disposition", `form-data; name="users"; filename="users.json"`)
header.Set("Content-Type", "application/json")

writer, err := mp.CreatePart(header)
if err != nil {
return err
}
w.Write(b)

if _, err := writer.Write(usersJSON); err != nil {
return err
}
}
if err := mp.Close(); err != nil {
return err
}

request, err := http.NewRequest("POST", m.URI("jobs", "users-imports"), &payload)
if err != nil {
return err
}
request.Header.Add("Content-Type", mp.FormDataContentType())

for _, option := range opts {
option.apply(request)
}

response, err := m.Do(request)
if err != nil {
return err
}
defer response.Body.Close()

if response.StatusCode >= http.StatusBadRequest {
return newError(response)
}
mp.Close()

opts = append(opts, Header("Content-Type", mp.FormDataContentType()))
if response.StatusCode != http.StatusNoContent {
return json.NewDecoder(response.Body).Decode(j)
}

return m.Request("POST", m.URI("jobs", "users-imports"), &payload, opts...)
return nil
}

0 comments on commit 43d9898

Please sign in to comment.