github.com/Axway/agent-sdk@v1.1.101/pkg/apic/apiserver/models/api/v1/owner.go (about)

     1  package v1
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  )
     7  
     8  type Organization struct {
     9  	ID string `json:"id"`
    10  }
    11  
    12  // OwnerType -
    13  type OwnerType uint
    14  
    15  const (
    16  	TeamOwner OwnerType = iota
    17  )
    18  
    19  var ownerTypeToString = map[OwnerType]string{
    20  	TeamOwner: "team",
    21  }
    22  
    23  var ownerTypeFromString = map[string]OwnerType{
    24  	"team": TeamOwner,
    25  }
    26  
    27  // Owner is the owner of a resource
    28  type Owner struct {
    29  	Type         OwnerType    `json:"type,omitempty"`
    30  	ID           string       `json:"id"`
    31  	Organization Organization `json:"organization,omitempty"`
    32  }
    33  
    34  // SetType sets the type of the owner
    35  func (o *Owner) SetType(t OwnerType) {
    36  	o.Type = t
    37  }
    38  
    39  // SetID sets the id of the owner
    40  func (o *Owner) SetID(id string) {
    41  	o.ID = id
    42  }
    43  
    44  // MarshalJSON marshals the owner to JSON
    45  func (o *Owner) MarshalJSON() ([]byte, error) {
    46  	var t string
    47  	var ok bool
    48  	if t, ok = ownerTypeToString[o.Type]; !ok {
    49  		t = ownerTypeToString[TeamOwner]
    50  	}
    51  
    52  	aux := struct {
    53  		Type         string        `json:"type,omitempty"`
    54  		ID           string        `json:"id"`
    55  		Organization *Organization `json:"organization,omitempty"`
    56  	}{}
    57  
    58  	aux.Type = t
    59  	aux.ID = o.ID
    60  	if o.Organization.ID != "" {
    61  		aux.Organization = &Organization{
    62  			ID: o.Organization.ID,
    63  		}
    64  	}
    65  
    66  	return json.Marshal(aux)
    67  }
    68  
    69  // UnmarshalJSON unmarshalls the owner from JSON to convert the owner type to a string
    70  func (o *Owner) UnmarshalJSON(bytes []byte) error {
    71  	aux := struct {
    72  		Type         string       `json:"type,omitempty"`
    73  		ID           string       `json:"id"`
    74  		Organization Organization `json:"organization,omitempty"`
    75  	}{}
    76  
    77  	if err := json.Unmarshal(bytes, &aux); err != nil {
    78  		return err
    79  	}
    80  
    81  	ownerType := TeamOwner
    82  	if aux.Type != "" {
    83  		var ok bool
    84  		ownerType, ok = ownerTypeFromString[aux.Type]
    85  		if !ok {
    86  			return fmt.Errorf("unknown owner type %s", aux.Type)
    87  		}
    88  	}
    89  	o.Type = ownerType
    90  	o.ID = aux.ID
    91  	o.Organization = aux.Organization
    92  
    93  	return nil
    94  }