Skip to content

Commit

Permalink
WIP 193
Browse files Browse the repository at this point in the history
  • Loading branch information
steve-r-west committed Nov 20, 2024
1 parent 99c7f35 commit 53c741e
Show file tree
Hide file tree
Showing 15 changed files with 628 additions and 519 deletions.
132 changes: 2 additions & 130 deletions cmd/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,13 @@ import (
gojson "encoding/json"
"fmt"
"github.com/elasticpath/epcc-cli/external/aliases"
"github.com/elasticpath/epcc-cli/external/autofill"
"github.com/elasticpath/epcc-cli/external/completion"
"github.com/elasticpath/epcc-cli/external/encoding"
"github.com/elasticpath/epcc-cli/external/httpclient"
"github.com/elasticpath/epcc-cli/external/json"
"github.com/elasticpath/epcc-cli/external/resources"
"github.com/elasticpath/epcc-cli/external/shutdown"
"github.com/elasticpath/epcc-cli/external/rest"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"io"
"net/http"
"net/url"
"strings"
)

Expand Down Expand Up @@ -105,7 +100,7 @@ func NewCreateCommand(parentCmd *cobra.Command) func() {
}
}

body, err := createInternal(context.Background(), overrides, append([]string{resourceName}, args...), autoFillOnCreate, setAlias, skipAliases)
body, err := rest.CreateInternal(context.Background(), overrides, append([]string{resourceName}, args...), autoFillOnCreate, setAlias, skipAliases)

if err != nil {
return err
Expand Down Expand Up @@ -241,126 +236,3 @@ func NewCreateCommand(parentCmd *cobra.Command) func() {

return resetFunc
}

func createInternal(ctx context.Context, overrides *httpclient.HttpParameterOverrides, args []string, autoFillOnCreate bool, aliasName string, skipAliases bool) (string, error) {
shutdown.OutstandingOpCounter.Add(1)
defer shutdown.OutstandingOpCounter.Done()

// Find Resource
resource, ok := resources.GetResourceByName(args[0])
if !ok {
return "", fmt.Errorf("could not find resource %s", args[0])
}

if resource.CreateEntityInfo == nil {
return "", fmt.Errorf("resource %s doesn't support CREATE", args[0])
}

// Count ids in CreateEntity
resourceURL := resource.CreateEntityInfo.Url

idCount, err := resources.GetNumberOfVariablesNeeded(resourceURL)

if err != nil {
return "", err
}

// Replace ids with args in resourceURL
resourceURL, err = resources.GenerateUrl(resource.CreateEntityInfo, args[1:], true)

if overrides.OverrideUrlPath != "" {
log.Warnf("Overriding URL Path from %s to %s", resourceURL, overrides.OverrideUrlPath)
resourceURL = overrides.OverrideUrlPath
}

if err != nil {
return "", err
}

var resp *http.Response = nil
var resBody []byte

if resource.CreateEntityInfo.ContentType == "multipart/form-data" {

byteBuf, contentType, err := encoding.ToMultiPartEncoding(args[(idCount+1):], resource.NoWrapping, resource.JsonApiFormat == "complaint", resource.Attributes)
if err != nil {
return "", err
}

// Submit request
resp, err = httpclient.DoFileRequest(ctx, resourceURL, byteBuf, contentType)

} else {
// Assume it's application/json

params := url.Values{}

for _, v := range overrides.QueryParameters {
keyAndValue := strings.SplitN(v, "=", 2)
if len(keyAndValue) != 2 {
return "", fmt.Errorf("Could not parse query parameter %v, all query parameters should be a key and value format", keyAndValue)
}
params.Add(keyAndValue[0], keyAndValue[1])
}

if !resource.NoWrapping {
args = append(args, "type", resource.JsonApiType)
}
// Create the body from remaining args

jsonArgs := args[(idCount + 1):]
if autoFillOnCreate {
autofilledData := autofill.GetJsonArrayForResource(&resource)

jsonArgs = append(autofilledData, jsonArgs...)
}

body, err := json.ToJson(jsonArgs, resource.NoWrapping, resource.JsonApiFormat == "compliant", resource.Attributes, true)

if err != nil {
return "", err
}

// Submit request
resp, err = httpclient.DoRequest(ctx, "POST", resourceURL, params.Encode(), strings.NewReader(body))

}

if err != nil {
return "", fmt.Errorf("got error %s", err.Error())
} else if resp == nil {
return "", fmt.Errorf("got nil response with request: %s", resourceURL)
}

if resp.Body != nil {
defer resp.Body.Close()

// Print the body
resBody, err = io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}

// Check if error response
if resp.StatusCode >= 400 && resp.StatusCode <= 600 {
json.PrintJson(string(resBody))
return "", fmt.Errorf(resp.Status)
}

// 204 is no content, so we will skip it.
if resp.StatusCode != 204 {
if !skipAliases {
aliases.SaveAliasesForResources(string(resBody))
}
}

if aliasName != "" {
aliases.SetAliasForResource(string(resBody), aliasName)
}

return string(resBody), nil
} else {
return "", nil
}

}
116 changes: 2 additions & 114 deletions cmd/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,9 @@ import (
"github.com/elasticpath/epcc-cli/external/httpclient"
"github.com/elasticpath/epcc-cli/external/json"
"github.com/elasticpath/epcc-cli/external/resources"
"github.com/elasticpath/epcc-cli/external/shutdown"
"github.com/elasticpath/epcc-cli/external/rest"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"io"
"net/http"
"net/url"
"strings"
)

func NewDeleteCommand(parentCmd *cobra.Command) func() {
Expand Down Expand Up @@ -94,7 +90,7 @@ func NewDeleteCommand(parentCmd *cobra.Command) func() {
}
}

body, err := deleteInternal(context.Background(), overrides, allow404, append([]string{resourceName}, args...))
body, err := rest.DeleteInternal(context.Background(), overrides, allow404, append([]string{resourceName}, args...))

if err != nil {
if body != "" {
Expand Down Expand Up @@ -193,111 +189,3 @@ func NewDeleteCommand(parentCmd *cobra.Command) func() {

return resetFunc
}
func deleteInternal(ctx context.Context, overrides *httpclient.HttpParameterOverrides, allow404 bool, args []string) (string, error) {
shutdown.OutstandingOpCounter.Add(1)
defer shutdown.OutstandingOpCounter.Done()

resource, ok := resources.GetResourceByName(args[0])
if !ok {
return "", fmt.Errorf("could not find resource %s", args[0])
}

resp, err := deleteResource(ctx, overrides, args)
if err != nil {
return "", err
}

if resp == nil {
return "", fmt.Errorf("got nil response")
}

if resp.StatusCode < 400 {
idToDelete := aliases.ResolveAliasValuesOrReturnIdentity(resource.JsonApiType, resource.AlternateJsonApiTypesForAliases, args[len(args)-1], "id")
aliases.DeleteAliasesById(idToDelete, resource.JsonApiType)
}
if resp.Body != nil {

defer resp.Body.Close()

// Print the body
body, err := io.ReadAll(resp.Body)

if err != nil {
log.Fatal(err)
}

// Check if error response
if resp.StatusCode >= 400 && resp.StatusCode <= 600 {
if resp.StatusCode != 404 || !allow404 {
return string(body), fmt.Errorf(resp.Status)
}
}

return string(body), nil
} else {
return "", nil
}

}

func deleteResource(ctx context.Context, overrides *httpclient.HttpParameterOverrides, args []string) (*http.Response, error) {
// Find Resource
resource, ok := resources.GetResourceByName(args[0])
if !ok {
return nil, fmt.Errorf("could not find resource %s", args[0])
}

if resource.DeleteEntityInfo == nil {
return nil, fmt.Errorf("resource %s doesn't support DELETE", args[0])
}

// Replace ids with args in resourceURL
resourceURL, err := resources.GenerateUrl(resource.DeleteEntityInfo, args[1:], true)

if err != nil {
return nil, err
}

if overrides.OverrideUrlPath != "" {
log.Warnf("Overriding URL Path from %s to %s", resourceURL, overrides.OverrideUrlPath)
resourceURL = overrides.OverrideUrlPath
}

params := url.Values{}

for _, v := range overrides.QueryParameters {
keyAndValue := strings.SplitN(v, "=", 2)
if len(keyAndValue) != 2 {
return nil, fmt.Errorf("Could not parse query parameter %v, all query parameters should be a key and value format", keyAndValue)
}
params.Add(keyAndValue[0], keyAndValue[1])
}

idCount, err := resources.GetNumberOfVariablesNeeded(resource.DeleteEntityInfo.Url)

if !resource.NoWrapping {
args = append(args, "type", resource.JsonApiType)
}
// Create the body from remaining args

jsonArgs := args[(idCount + 1):]

var payload io.Reader = nil
if len(jsonArgs) > 0 {
body, err := json.ToJson(jsonArgs, resource.NoWrapping, resource.JsonApiFormat == "compliant", resource.Attributes, true)

if err != nil {
return nil, err
}

payload = strings.NewReader(body)
}

// Submit request
resp, err := httpclient.DoRequest(ctx, "DELETE", resourceURL, params.Encode(), payload)
if err != nil {
return nil, fmt.Errorf("got error %s", err.Error())
}

return resp, nil
}
Loading

0 comments on commit 53c741e

Please sign in to comment.