github.com/qri-io/qri@v0.10.1-0.20220104210721-c771715036cb/profile/type.go (about) 1 package profile 2 3 import ( 4 "encoding/json" 5 "fmt" 6 ) 7 8 // Type enumerates different types of peers 9 type Type int 10 11 const ( 12 // TypePeer is a single person 13 TypePeer Type = iota 14 // TypeOrganization represents a group of people 15 TypeOrganization 16 ) 17 18 // String implements the Stringer interface for Type 19 func (t Type) String() string { 20 switch t { 21 case TypePeer: 22 return "peer" 23 case TypeOrganization: 24 return "organization" 25 } 26 27 return "unknown" 28 } 29 30 // ParseType decodes a peer type from a string 31 func ParseType(t string) (Type, error) { 32 got, ok := map[string]Type{"": TypePeer, "user": TypePeer, "peer": TypePeer, "organization": TypeOrganization}[t] 33 if !ok { 34 return TypePeer, fmt.Errorf("invalid Type %q", t) 35 } 36 37 return got, nil 38 } 39 40 // MarshalJSON implements the json.Marshaler interface for Type 41 func (t Type) MarshalJSON() ([]byte, error) { 42 s, ok := map[Type]string{TypePeer: "peer", TypeOrganization: "organization"}[t] 43 if !ok { 44 return nil, fmt.Errorf("invalid Type %d", t) 45 } 46 47 return []byte(fmt.Sprintf(`"%s"`, s)), nil 48 } 49 50 // UnmarshalJSON implements the json.Unmarshaler interface for Type 51 func (t *Type) UnmarshalJSON(data []byte) (err error) { 52 var s string 53 if err := json.Unmarshal(data, &s); err != nil { 54 return fmt.Errorf("Peer type should be a string, got %s", data) 55 } 56 *t, err = ParseType(s) 57 return err 58 }