github.com/cloudfoundry-community/cloudfoundry-cli@v6.44.1-0.20240130060226-cda5ed8e89a5+incompatible/resources/relationship_resource.go (about) 1 package resources 2 3 import ( 4 "encoding/json" 5 6 "code.cloudfoundry.org/cli/api/cloudcontroller" 7 "code.cloudfoundry.org/cli/api/cloudcontroller/ccv3/constant" 8 ) 9 10 // Relationships represent associations between resources. Relationships is a 11 // map of RelationshipTypes to Relationship. 12 type Relationships map[constant.RelationshipType]Relationship 13 14 // Relationship represents a one to one relationship. 15 // An empty GUID will be marshaled as `null`. 16 type Relationship struct { 17 GUID string 18 } 19 20 func (r Relationship) MarshalJSON() ([]byte, error) { 21 if r.GUID == "" { 22 var emptyCCRelationship struct { 23 Data interface{} `json:"data"` 24 } 25 return json.Marshal(emptyCCRelationship) 26 } 27 28 var ccRelationship struct { 29 Data struct { 30 GUID string `json:"guid"` 31 } `json:"data"` 32 } 33 34 ccRelationship.Data.GUID = r.GUID 35 return json.Marshal(ccRelationship) 36 } 37 38 func (r *Relationship) UnmarshalJSON(data []byte) error { 39 var ccRelationship struct { 40 Data struct { 41 GUID string `json:"guid"` 42 } `json:"data"` 43 } 44 45 err := cloudcontroller.DecodeJSON(data, &ccRelationship) 46 if err != nil { 47 return err 48 } 49 50 r.GUID = ccRelationship.Data.GUID 51 return nil 52 } 53 54 // RelationshipList represents a one to many relationship. 55 type RelationshipList struct { 56 GUIDs []string 57 } 58 59 func (r RelationshipList) MarshalJSON() ([]byte, error) { 60 var ccRelationship struct { 61 Data []map[string]string `json:"data"` 62 } 63 64 for _, guid := range r.GUIDs { 65 ccRelationship.Data = append( 66 ccRelationship.Data, 67 map[string]string{ 68 "guid": guid, 69 }) 70 } 71 72 return json.Marshal(ccRelationship) 73 } 74 75 func (r *RelationshipList) UnmarshalJSON(data []byte) error { 76 var ccRelationships struct { 77 Data []map[string]string `json:"data"` 78 } 79 80 err := cloudcontroller.DecodeJSON(data, &ccRelationships) 81 if err != nil { 82 return err 83 } 84 85 for _, partner := range ccRelationships.Data { 86 r.GUIDs = append(r.GUIDs, partner["guid"]) 87 } 88 return nil 89 }