Skip to content

Commit

Permalink
chore: Clearest implementation of urn package.
Browse files Browse the repository at this point in the history
  • Loading branch information
x1m3 committed Jun 28, 2024
1 parent 27803b8 commit 785b0ee
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 8 deletions.
2 changes: 1 addition & 1 deletion internal/core/services/claims.go
Original file line number Diff line number Diff line change
Expand Up @@ -653,7 +653,7 @@ func (c *claim) getAgentCredential(ctx context.Context, basicMessage *ports.Agen
return nil, fmt.Errorf("invalid credential fetch request body: %w", err)
}

claimID, err := urn.Parse(urn.URN(fetchRequestBody.ID))
claimID, err := urn.UUIDFromURNString(fetchRequestBody.ID)
if err != nil {
claimID, err = uuid.Parse(fetchRequestBody.ID)
if err != nil {
Expand Down
34 changes: 29 additions & 5 deletions internal/urn/urn.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,37 @@ func FromUUID(uuid uuid.UUID) URN {
return URN("urn:uuid:" + uuid.String())
}

// Parse extracts a UUID from a URN.
func Parse(u URN) (uuid.UUID, error) {
// UUID returns the UUID from a URN. It can throw an error to prevent bad constructor calls or urns without uuids
func (u URN) UUID() (uuid.UUID, error) {
if err := u.valid(); err != nil {
return uuid.Nil, err
}
return uuid.Parse(string(u[9:]))
}

func (u URN) valid() error {
if len(u) < len("urn:uuid:") {
return uuid.UUID{}, errors.New("invalid uuid URN length")
return errors.New("invalid uuid URN length")
}
if u[:9] != "urn:uuid:" {
return uuid.UUID{}, errors.New("invalid uuid URN prefix")
return errors.New("invalid uuid URN prefix")
}
return uuid.Parse(string(u[9:]))
return nil
}

// Parse creates a URN from a string.
func Parse(u string) (URN, error) {
if err := URN(u).valid(); err != nil {
return "", err
}
return URN(u), nil
}

// UUIDFromURNString returns the UUID from a URN string.
func UUIDFromURNString(s string) (uuid.UUID, error) {
urn, err := Parse(s)
if err != nil {
return uuid.Nil, err
}
return urn.UUID()
}
4 changes: 2 additions & 2 deletions internal/urn/urn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ func TestFromUUID(t *testing.T) {
assert.Equal(t, "urn:uuid:"+id.String(), string(urn))
}

func TestParse(t *testing.T) {
func TestUUIDFromURNString(t *testing.T) {
for _, ts := range []struct {
urn string
err error
Expand All @@ -25,7 +25,7 @@ func TestParse(t *testing.T) {
{"urn:uuid:123e4567-e89b-12d3-a456-426614174000", nil},
} {
t.Run(ts.urn, func(t *testing.T) {
u, err := Parse(URN(ts.urn))
u, err := UUIDFromURNString(ts.urn)
if err == nil {
assert.Equal(t, ts.urn[9:], u.String())
} else {
Expand Down

0 comments on commit 785b0ee

Please sign in to comment.