Skip to content

Commit

Permalink
feat: add upsert method and enable it for environments (#2746)
Browse files Browse the repository at this point in the history
* add upsert method and enable it for environments

* handle error when getting entity
  • Loading branch information
mathnogueira authored Jun 16, 2023
1 parent 887b34c commit c519fff
Show file tree
Hide file tree
Showing 6 changed files with 97 additions and 33 deletions.
18 changes: 1 addition & 17 deletions cli/actions/environments.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package actions

import (
"context"
"errors"
"fmt"
"io/ioutil"

Expand Down Expand Up @@ -52,22 +51,7 @@ func (environment environmentsActions) Apply(ctx context.Context, fileContent fi

mapstructure.Decode(fileContent.Definition().Spec, &envResource.Spec)

if envResource.Spec.GetId() != "" {
_, err := environment.Get(ctx, envResource.Spec.GetId())
if err != nil {
if !errors.Is(err, utils.ResourceNotFound) {
return nil, err
}

// doesn't exist, so create it
return environment.resourceClient.Create(ctx, fileContent)
}

return environment.resourceClient.Update(ctx, fileContent, envResource.Spec.GetId())
}

result, err = environment.resourceClient.Create(ctx, fileContent)
return result, err
return environment.resourceClient.Upsert(ctx, fileContent)
}

func (environment environmentsActions) List(ctx context.Context, listArgs utils.ListArgs) (*file.File, error) {
Expand Down
30 changes: 30 additions & 0 deletions cli/utils/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -295,3 +295,33 @@ func (resourceClient ResourceClient) Create(ctx context.Context, file file.File)
file = file.SaveChanges(IOReadCloserToString(resp.Body))
return &file, nil
}

func (resourceClient ResourceClient) Upsert(ctx context.Context, file file.File) (*file.File, error) {
request, err := resourceClient.NewRequest(resourceClient.BaseUrl, http.MethodPut, file.Contents(), file.ContentType(), false)
if err != nil {
return nil, fmt.Errorf("could not create request: %w", err)
}

resp, err := resourceClient.Client.Do(request)
if err != nil {
return nil, fmt.Errorf("could not send request: %w", err)
}

defer resp.Body.Close()
if resp.StatusCode == http.StatusUnprocessableEntity {
// validation error
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("could not send request: %w", err)
}

validationError := string(body)
return nil, fmt.Errorf("invalid %s: %s", resourceClient.ResourceType, validationError)
}
if err != nil {
return nil, fmt.Errorf("could not create %s: %w", resourceClient.ResourceType, err)
}

file = file.SaveChanges(IOReadCloserToString(resp.Body))
return &file, nil
}
24 changes: 8 additions & 16 deletions server/environment/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,10 @@ const (

updateQuery = `
UPDATE environments SET
"id" = $2,
"name" = $3,
"description" = $4,
"created_at" = $5,
"values" = $6
"name" = $2,
"description" = $3,
"created_at" = $4,
"values" = $5
WHERE id = $1
`

Expand Down Expand Up @@ -74,18 +73,12 @@ func (r *Repository) SetID(environment Environment, id id.ID) Environment {
}

func (r *Repository) Create(ctx context.Context, environment Environment) (Environment, error) {
environment.ID = environment.Slug()
_, err := r.Get(ctx, environment.ID)
if err != nil {
if err == sql.ErrNoRows {
environment.CreatedAt = time.Now().UTC().Format(time.RFC3339Nano)
return r.insertIntoEnvironments(ctx, environment)
}

return Environment{}, err
if !environment.HasID() {
environment.ID = environment.Slug()
}

return r.Update(ctx, environment)
environment.CreatedAt = time.Now().UTC().Format(time.RFC3339Nano)
return r.insertIntoEnvironments(ctx, environment)
}

func (r *Repository) Update(ctx context.Context, environment Environment) (Environment, error) {
Expand Down Expand Up @@ -309,7 +302,6 @@ func (r *Repository) updateIntoEnvironments(ctx context.Context, environment Env
_, err = stmt.ExecContext(
ctx,
oldId,
environment.Slug(),
environment.Name,
environment.Description,
environment.CreatedAt,
Expand Down
1 change: 1 addition & 0 deletions server/environment/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const (

var Operations = []resourcemanager.Operation{
resourcemanager.OperationCreate,
resourcemanager.OperationUpsert,
resourcemanager.OperationDelete,
resourcemanager.OperationGet,
resourcemanager.OperationList,
Expand Down
1 change: 1 addition & 0 deletions server/resourcemanager/operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const (
OperationNoop Operation = ""
OperationList Operation = "list"
OperationCreate Operation = "create"
OperationUpsert Operation = "upsert"
OperationUpdate Operation = "update"
OperationGet Operation = "get"
OperationDelete Operation = "delete"
Expand Down
56 changes: 56 additions & 0 deletions server/resourcemanager/resource_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,10 @@ func (m *manager[T]) RegisterRoutes(r *mux.Router) *mux.Router {
m.instrumentRoute(subrouter.HandleFunc("", m.create).Methods(http.MethodPost).Name(fmt.Sprintf("%s.Create", m.resourceTypePlural)))
}

if slices.Contains(enabledOps, OperationUpsert) {
m.instrumentRoute(subrouter.HandleFunc("", m.upsert).Methods(http.MethodPut).Name(fmt.Sprintf("%s.Upsert", m.resourceTypePlural)))
}

if slices.Contains(enabledOps, OperationUpdate) {
m.instrumentRoute(subrouter.HandleFunc("/{id}", m.update).Methods(http.MethodPut).Name(fmt.Sprintf("%s.Update", m.resourceTypePlural)))
}
Expand Down Expand Up @@ -235,6 +239,58 @@ func (m *manager[T]) create(w http.ResponseWriter, r *http.Request) {
}
}

func (m *manager[T]) upsert(w http.ResponseWriter, r *http.Request) {
encoder := EncoderFromRequest(r)

targetResource := Resource[T]{}
err := encoder.DecodeRequestBody(&targetResource)
if err != nil {
writeError(w, encoder, http.StatusBadRequest, fmt.Errorf("cannot parse body: %w", err))
return
}

if !targetResource.Spec.HasID() {
targetResource.Spec = m.rh.SetID(targetResource.Spec, m.config.idgen())
}

writeResponse := func(status int, spec T) {
newResource := Resource[T]{
Type: m.resourceTypeSingular,
Spec: spec,
}

err = encoder.WriteEncodedResponse(w, status, newResource)
if err != nil {
writeError(w, encoder, http.StatusInternalServerError, fmt.Errorf("cannot marshal entity: %w", err))
}
}

_, err = m.rh.Get(r.Context(), targetResource.Spec.GetID())
if err != nil {
if err == sql.ErrNoRows {
created, err := m.rh.Create(r.Context(), targetResource.Spec)
if err != nil {
writeError(w, encoder, http.StatusInternalServerError, fmt.Errorf("cannot create entity: %w", err))
return
}

writeResponse(http.StatusCreated, created)
return
} else {
writeError(w, encoder, http.StatusInternalServerError, fmt.Errorf("could not get entity: %w", err))
return
}
}

updated, err := m.rh.Update(r.Context(), targetResource.Spec)
if err != nil {
writeError(w, encoder, http.StatusInternalServerError, err)
return
}

writeResponse(http.StatusOK, updated)
}

func (m *manager[T]) update(w http.ResponseWriter, r *http.Request) {
encoder := EncoderFromRequest(r)

Expand Down

0 comments on commit c519fff

Please sign in to comment.