github.com/kyleu/dbaudit@v0.0.2-0.20240321155047-ff2f2c940496/app/lib/schema/field/field.go (about)

     1  // Package field - Content managed by Project Forge, see [projectforge.md] for details.
     2  package field
     3  
     4  import (
     5  	"reflect"
     6  
     7  	"github.com/samber/lo"
     8  
     9  	"github.com/kyleu/dbaudit/app/lib/types"
    10  	"github.com/kyleu/dbaudit/app/util"
    11  )
    12  
    13  type Field struct {
    14  	Key      string         `json:"key"`
    15  	Type     *types.Wrapped `json:"type"`
    16  	Title    string         `json:"-"` // override only
    17  	Plural   string         `json:"-"` // override only
    18  	Hidden   bool           `json:"-"` // override only
    19  	Default  any            `json:"default,omitempty"`
    20  	ReadOnly bool           `json:"readOnly,omitempty"`
    21  	Metadata *Metadata      `json:"metadata,omitempty"`
    22  }
    23  
    24  func NewFieldByType(key string, t reflect.Type, ro bool, md *Metadata) *Field {
    25  	return &Field{Key: key, Type: types.FromReflect(t), ReadOnly: ro, Metadata: md}
    26  }
    27  
    28  func (f *Field) Name() string {
    29  	if f.Title == "" {
    30  		return util.StringToSingular(util.StringToTitle(f.Key))
    31  	}
    32  	return f.Title
    33  }
    34  
    35  func (f *Field) PluralName() string {
    36  	if f.Plural == "" {
    37  		ret := f.Name()
    38  		return util.StringToPlural(ret)
    39  	}
    40  	return f.Plural
    41  }
    42  
    43  func (f *Field) String() string {
    44  	return f.Key + " " + f.Type.String()
    45  }
    46  
    47  func (f *Field) Description() string {
    48  	if f.Metadata == nil {
    49  		return ""
    50  	}
    51  	return f.Metadata.Description
    52  }
    53  
    54  func (f *Field) DefaultClean() any {
    55  	switch f.Default {
    56  	case nil:
    57  		return f.Type.Default(f.Key)
    58  	case "now()":
    59  		return util.TimeCurrent()
    60  	default:
    61  		return f.Default
    62  	}
    63  }
    64  
    65  type Fields []*Field
    66  
    67  func (s Fields) Get(key string) (int, *Field) {
    68  	for idx, x := range s {
    69  		if x.Key == key {
    70  			return idx, x
    71  		}
    72  	}
    73  	return -1, nil
    74  }
    75  
    76  func (s Fields) Names() []string {
    77  	return lo.Map(s, func(x *Field, _ int) string {
    78  		return x.Key
    79  	})
    80  }