Skip to content

Commit

Permalink
Add self link mapper
Browse files Browse the repository at this point in the history
  • Loading branch information
Daishan committed Feb 19, 2021
1 parent 63e1cb5 commit f6cec23
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
1 change: 1 addition & 0 deletions types/mapper/object.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ func NewObject(mappers ...types.Mapper) Object {
Mappers: append([]types.Mapper{
&APIGroup{},
&Embed{Field: "metadata"},
&SelfLink{},
&Embed{Field: "spec", Optional: true},
&ReadOnly{Field: "status", Optional: true, SubFields: true},
Drop{Field: "kind"},
Expand Down
52 changes: 52 additions & 0 deletions types/mapper/selflink.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package mapper

import (
"github.com/rancher/wrangler/pkg/name"
"strings"

"github.com/rancher/norman/types"
)

type SelfLink struct {
resource string
}

func (s *SelfLink) FromInternal(data map[string]interface{}) {
sl, ok := data["selfLink"].(string)
if !ok || sl == "" {
data["selfLink"] = s.selflink(data)
}
}

func (s *SelfLink) ToInternal(data map[string]interface{}) error {
return nil
}

func (s *SelfLink) ModifySchema(schema *types.Schema, schemas *types.Schemas) error {
s.resource = name.GuessPluralName(schema.ID)
return nil
}

func (s *SelfLink) selflink(data map[string]interface{}) string {
buf := &strings.Builder{}
name := data["name"].(string)
apiVersion, ok := data["apiVersion"].(string)
if !ok || apiVersion == "v1" {
buf.WriteString("/api/v1/")
} else {
buf.WriteString("/apis/")
buf.WriteString(apiVersion)
buf.WriteString("/")
}
namespace, ok := data["namespace"].(string)
if !ok || namespace != "" {
buf.WriteString("namespaces/")
buf.WriteString(namespace)
buf.WriteString("/")
}
buf.WriteString(s.resource)
buf.WriteString("/")
buf.WriteString(name)
return buf.String()
}

0 comments on commit f6cec23

Please sign in to comment.