From 0babaa518db6cbdc17779e9c4846a8a277d098b7 Mon Sep 17 00:00:00 2001 From: mo khan Date: Thu, 24 Jul 2025 16:49:01 -0600 Subject: feat: create a GlobalID type --- app/domain/global_id.go | 31 +++++++++++++++++++++++++++++++ app/domain/global_id_test.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 app/domain/global_id.go create mode 100644 app/domain/global_id_test.go (limited to 'app') diff --git a/app/domain/global_id.go b/app/domain/global_id.go new file mode 100644 index 0000000..de0093d --- /dev/null +++ b/app/domain/global_id.go @@ -0,0 +1,31 @@ +package domain + +import ( + "net/url" + "strings" + + v1 "github.com/authzed/authzed-go/proto/authzed/api/v1" +) + +type GlobalID string + +func (self GlobalID) String() string { + return string(self) +} + +func (self GlobalID) ToObjectReference() *v1.ObjectReference { + url, err := url.Parse(self.String()) + if err != nil { + return &v1.ObjectReference{} + } + + segments := strings.SplitN(url.Path, "/", 3) + if len(segments) < 3 { + return &v1.ObjectReference{} + } + + return &v1.ObjectReference{ + ObjectType: strings.ToLower(segments[1]), + ObjectId: segments[2], + } +} diff --git a/app/domain/global_id_test.go b/app/domain/global_id_test.go new file mode 100644 index 0000000..e678e6c --- /dev/null +++ b/app/domain/global_id_test.go @@ -0,0 +1,44 @@ +package domain + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestGlobalID(t *testing.T) { + + t.Run("ToObjectReference", func(t *testing.T) { + tt := []struct { + input string + id string + oType string + isValid bool + }{ + {"gid://app/Sparkle/1", "1", "sparkle", true}, + {"gid://example/sparkle/1", "1", "sparkle", true}, + {"gid://example/sparkle/696266fc-68df-11f0-bbc2-7ec11f4b308c", "696266fc-68df-11f0-bbc2-7ec11f4b308c", "sparkle", true}, + {"gid://example/User/tanuki", "tanuki", "user", true}, + {"", "", "", false}, + {"gid://example", "", "", false}, + {"gid://example/Example", "", "", false}, + } + + for _, example := range tt { + t.Run(example.input, func(t *testing.T) { + reference := GlobalID(example.input).ToObjectReference() + + require.NotNil(t, reference) + assert.Equal(t, example.id, reference.GetObjectId()) + assert.Equal(t, example.oType, reference.GetObjectType()) + + if example.isValid { + require.NoError(t, reference.Validate()) + } else { + require.Error(t, reference.Validate()) + } + }) + } + }) +} -- cgit v1.2.3