Skip to content

Commit

Permalink
feat: add AddReference method to References
Browse files Browse the repository at this point in the history
Signed-off-by: Yordis Prieto <[email protected]>
  • Loading branch information
yordis committed Jun 2, 2024
1 parent 4073347 commit 3da3f28
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
16 changes: 16 additions & 0 deletions pkg/config/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,10 +165,26 @@ type ExternalName struct {
IdentifierFields []string
}

var ErrReferenceAlreadyExists = errors.New("reference for field already exists")

// References represents reference resolver configurations for the fields of a
// given resource. Key should be the field path of the field to be referenced.
type References map[string]Reference

// AddReference adds a reference configuration for the given field path.
// The fieldPath is the Terraform field path of the field to be referenced.
//
// Example: "vpc_id" or "forwarding_rule.certificate_name" in case of nested
// in another object.
func (r References) AddReference(fieldPath string, ref Reference) error {
if _, ok := r[fieldPath]; ok {
return ErrReferenceAlreadyExists
}

r[fieldPath] = ref
return nil
}

// Reference represents the Crossplane options used to generate
// reference resolvers for fields
type Reference struct {
Expand Down
33 changes: 32 additions & 1 deletion pkg/config/resource_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ package config

import (
"context"
"errors"
"fmt"
"testing"

"github.com/crossplane/crossplane-runtime/pkg/errors"
"github.com/crossplane/crossplane-runtime/pkg/fieldpath"
xpresource "github.com/crossplane/crossplane-runtime/pkg/resource"
"github.com/crossplane/crossplane-runtime/pkg/resource/fake"
Expand Down Expand Up @@ -112,3 +112,34 @@ func TestSetExternalTagsWithPaved(t *testing.T) {
})
}
}

func TestReferences_AddReference(t *testing.T) {
t.Run("Adding a reference", func(t *testing.T) {
r := &Resource{References: References{}}
err := r.References.AddReference("forwarding_rule.certificate_name", Reference{
TerraformName: "digitalocean_certificate",
})
if err != nil {
t.Fatalf("AddReference() got error: %v", err)
}
if len(r.References) != 1 {
t.Fatalf("AddReference() got error: %v", err)
}
})
t.Run("Adding twice a reference for a given field", func(t *testing.T) {
r := &Resource{References: References{}}
err := r.References.AddReference("forwarding_rule.certificate_name", Reference{
TerraformName: "digitalocean_certificate",
})
if err != nil {
t.Fatalf("AddReference() got error: %v", err)
}

err = r.References.AddReference("forwarding_rule.certificate_name", Reference{
TerraformName: "digitalocean_certificate",
})
if !errors.Is(err, ErrReferenceAlreadyExists) {
t.Fatalf("AddReference() should have returned an error")
}
})
}

0 comments on commit 3da3f28

Please sign in to comment.