Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 20 additions & 36 deletions force/api.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
package force

import (
"context"
"fmt"
"net/http"
"sync"

"golang.org/x/oauth2/jwt"
)

const (
Expand All @@ -19,21 +24,22 @@ const (
)

type ForceApi struct {
client *http.Client
jwtConfig *jwt.Config
jwtMutex sync.Mutex
apiVersion string
oauth *forceOauth
InstanceURL string
apiResources map[string]string
apiSObjects map[string]*SObjectMetaData
apiSObjectDescriptions map[string]*SObjectDescription
apiMaxBatchSize int64
logger ForceApiLogger
logPrefix string
disableForceAutoAssign bool
}

type RefreshTokenResponse struct {
ID string `json:"id"`
IssuedAt string `json:"issued_at"`
Signature string `json:"signature"`
AccessToken string `json:"access_token"`
func (f *ForceApi) SetClient(client *http.Client) {
f.client = client
}

type SObjectApiResponse struct {
Expand Down Expand Up @@ -170,17 +176,17 @@ type ChildRelationship struct {
RelationshipName string `json:"relationshipName"`
}

func (forceApi *ForceApi) getApiResources() error {
func (forceApi *ForceApi) getApiResources(ctx context.Context) error {
uri := fmt.Sprintf(resourcesUri, forceApi.apiVersion)

return forceApi.Get(uri, nil, &forceApi.apiResources)
return forceApi.Get(ctx, uri, nil, &forceApi.apiResources)
}

func (forceApi *ForceApi) getApiSObjects() error {
func (forceApi *ForceApi) getApiSObjects(ctx context.Context) error {
uri := forceApi.apiResources[sObjectsKey]

list := &SObjectApiResponse{}
err := forceApi.Get(uri, nil, list)
err := forceApi.Get(ctx, uri, nil, list)
if err != nil {
return err
}
Expand All @@ -195,12 +201,12 @@ func (forceApi *ForceApi) getApiSObjects() error {
return nil
}

func (forceApi *ForceApi) getApiSObjectDescriptions() error {
func (forceApi *ForceApi) getApiSObjectDescriptions(ctx context.Context) error {
for name, metaData := range forceApi.apiSObjects {
uri := metaData.URLs[sObjectDescribeKey]

desc := &SObjectDescription{}
err := forceApi.Get(uri, nil, desc)
err := forceApi.Get(ctx, uri, nil, desc)
if err != nil {
return err
}
Expand All @@ -211,28 +217,6 @@ func (forceApi *ForceApi) getApiSObjectDescriptions() error {
return nil
}

func (forceApi *ForceApi) GetInstanceURL() string {
return forceApi.oauth.InstanceUrl
}

func (forceApi *ForceApi) GetAccessToken() string {
return forceApi.oauth.AccessToken
}

func (forceApi *ForceApi) RefreshToken() error {
res := &RefreshTokenResponse{}
payload := map[string]string{
"grant_type": "refresh_token",
"refresh_token": forceApi.oauth.refreshToken,
"client_id": forceApi.oauth.clientId,
"client_secret": forceApi.oauth.clientSecret,
}

err := forceApi.Post("/services/oauth2/token", nil, payload, res)
if err != nil {
return err
}

forceApi.oauth.AccessToken = res.AccessToken
return nil
func (forceApi *ForceApi) SetDisableForceAutoAssign(value bool) {
forceApi.disableForceAutoAssign = value
}
70 changes: 39 additions & 31 deletions force/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ package force

import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"

"github.com/nimajalali/go-force/forcejson"
"github.com/pwaterz/go-force/forcejson"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
)

const (
Expand All @@ -20,41 +22,37 @@ const (

// Get issues a GET to the specified path with the given params and put the
// umarshalled (json) result in the third parameter
func (forceApi *ForceApi) Get(path string, params url.Values, out interface{}) error {
return forceApi.request("GET", path, params, nil, out)
func (forceApi *ForceApi) Get(ctx context.Context, path string, params url.Values, out interface{}) error {
return forceApi.request(ctx, "GET", path, params, nil, out, false)
}

// Post issues a POST to the specified path with the given params and payload
// and put the unmarshalled (json) result in the third parameter
func (forceApi *ForceApi) Post(path string, params url.Values, payload, out interface{}) error {
return forceApi.request("POST", path, params, payload, out)
func (forceApi *ForceApi) Post(ctx context.Context, path string, params url.Values, payload, out interface{}) error {
return forceApi.request(ctx, "POST", path, params, payload, out, false)
}

// Put issues a PUT to the specified path with the given params and payload
// and put the unmarshalled (json) result in the third parameter
func (forceApi *ForceApi) Put(path string, params url.Values, payload, out interface{}) error {
return forceApi.request("PUT", path, params, payload, out)
func (forceApi *ForceApi) Put(ctx context.Context, path string, params url.Values, payload, out interface{}) error {
return forceApi.request(ctx, "PUT", path, params, payload, out, false)
}

// Patch issues a PATCH to the specified path with the given params and payload
// and put the unmarshalled (json) result in the third parameter
func (forceApi *ForceApi) Patch(path string, params url.Values, payload, out interface{}) error {
return forceApi.request("PATCH", path, params, payload, out)
func (forceApi *ForceApi) Patch(ctx context.Context, path string, params url.Values, payload, out interface{}) error {
return forceApi.request(ctx, "PATCH", path, params, payload, out, false)
}

// Delete issues a DELETE to the specified path with the given payload
func (forceApi *ForceApi) Delete(path string, params url.Values) error {
return forceApi.request("DELETE", path, params, nil, nil)
func (forceApi *ForceApi) Delete(ctx context.Context, path string, params url.Values) error {
return forceApi.request(ctx, "DELETE", path, params, nil, nil, false)
}

func (forceApi *ForceApi) request(method, path string, params url.Values, payload, out interface{}) error {
if err := forceApi.oauth.Validate(); err != nil {
return fmt.Errorf("Error creating %v request: %v", method, err)
}

func (forceApi *ForceApi) request(ctx context.Context, method, path string, params url.Values, payload, out interface{}, retry bool) error {
// Build Uri
var uri bytes.Buffer
uri.WriteString(forceApi.oauth.InstanceUrl)
uri.WriteString(forceApi.InstanceURL)
uri.WriteString(path)
if params != nil && len(params) != 0 {
uri.WriteString("?")
Expand All @@ -74,7 +72,8 @@ func (forceApi *ForceApi) request(method, path string, params url.Values, payloa
}

// Build Request
req, err := http.NewRequest(method, uri.String(), body)
uriString := uri.String()
req, err := http.NewRequestWithContext(ctx, method, uriString, body)
if err != nil {
return fmt.Errorf("Error creating %v request: %v", method, err)
}
Expand All @@ -83,14 +82,27 @@ func (forceApi *ForceApi) request(method, path string, params url.Values, payloa
req.Header.Set("User-Agent", userAgent)
req.Header.Set("Content-Type", contentType)
req.Header.Set("Accept", responseType)
req.Header.Set("Authorization", fmt.Sprintf("%v %v", "Bearer", forceApi.oauth.AccessToken))

// Set this for this request only if requested by caller (if this header is set, OwnerId of created case
// will be set to the one we are passing in the request; if header not set, OwnerId is overwritten using SF rules)
if forceApi.disableForceAutoAssign {
fmt.Println("Disabling force auto assign")
req.Header.Set("Sforce-Auto-Assign", "False")
forceApi.SetDisableForceAutoAssign(false)
}

// Send
forceApi.traceRequest(req)
resp, err := http.DefaultClient.Do(req)
span, ctx := tracer.StartSpanFromContext(ctx, "Salesforce API Request", tracer.ResourceName(uriString))
span.SetTag("url", uriString)
span.SetTag("http_method", method)
resp, err := forceApi.client.Do(req)
if err != nil {
return fmt.Errorf("Error sending %v request: %v", method, err)
returnErr := fmt.Errorf("Error sending %v request: %v", method, err)
span.Finish(tracer.WithError(returnErr))
return returnErr
}
span.Finish()
defer resp.Body.Close()
forceApi.traceResponse(resp)

Expand Down Expand Up @@ -118,17 +130,13 @@ func (forceApi *ForceApi) request(method, path string, params url.Values, payloa
apiErrors := ApiErrors{}
if marshalErr := forcejson.Unmarshal(respBytes, &apiErrors); marshalErr == nil {
if apiErrors.Validate() {
// Check if error is oauth token expired
if forceApi.oauth.Expired(apiErrors) {
// Reauthenticate then attempt query again
oauthErr := forceApi.oauth.Authenticate()
if oauthErr != nil {
return oauthErr
}

return forceApi.request(method, path, params, payload, out)
// Deal with expired salesforce tokens
if apiErrors[0].ErrorCode == "INVALID_SESSION_ID" && !retry {
forceApi.jwtMutex.Lock()
forceApi.client = forceApi.jwtConfig.Client(ctx)
forceApi.jwtMutex.Unlock()
return forceApi.request(ctx, method, path, params, payload, out, true)
}

return apiErrors
}
}
Expand Down
Loading