github.com/friesencr/pop/v6@v6.1.6/genny/model/options.go (about) 1 package model 2 3 import ( 4 "errors" 5 "fmt" 6 "path/filepath" 7 "strings" 8 9 "github.com/gobuffalo/attrs" 10 ) 11 12 // Options for generating a new model 13 type Options struct { 14 Name string `json:"name"` 15 Attrs attrs.Attrs `json:"props"` 16 Path string `json:"path"` 17 Package string `json:"package"` 18 TestPackage string `json:"test_package"` 19 Encoding string `json:"encoding"` 20 ForceDefaultID bool `json:"force_default_id"` 21 ForceDefaultTimestamps bool `json:"force_default_timestamps"` 22 } 23 24 // Validate that options are usable 25 func (opts *Options) Validate() error { 26 if len(opts.Name) == 0 { 27 return errors.New("you must set a name for your model") 28 } 29 if len(opts.Path) == 0 { 30 opts.Path = "models" 31 } 32 if len(opts.Package) == 0 { 33 opts.Package = filepath.Base(opts.Path) 34 } 35 if len(opts.TestPackage) == 0 { 36 opts.TestPackage = opts.Package 37 } 38 if len(opts.Encoding) == 0 { 39 opts.Encoding = "json" 40 } 41 opts.Encoding = strings.ToLower(opts.Encoding) 42 if opts.Encoding != "json" && opts.Encoding != "jsonapi" && opts.Encoding != "xml" { 43 return fmt.Errorf("unsupported encoding option %s", opts.Encoding) 44 } 45 46 return opts.forceDefaults() 47 } 48 49 func (opts *Options) forceDefaults() error { 50 var idFound, createdAtFound, updatedAtFound bool 51 for _, a := range opts.Attrs { 52 switch a.Name.Underscore().String() { 53 case "id": 54 idFound = true 55 case "created_at": 56 createdAtFound = true 57 case "updated_at": 58 updatedAtFound = true 59 } 60 } 61 // Add a default UUID, if no custom ID is provided 62 if opts.ForceDefaultID && !idFound { 63 id, err := attrs.Parse("id:uuid") 64 if err != nil { 65 return err 66 } 67 opts.Attrs = append([]attrs.Attr{id}, opts.Attrs...) 68 } 69 70 // Add default timestamp columns if they were not provided 71 if opts.ForceDefaultTimestamps && !createdAtFound { 72 createdAt, err := attrs.Parse("created_at:time") 73 if err != nil { 74 return err 75 } 76 opts.Attrs = append(opts.Attrs, createdAt) 77 } 78 if opts.ForceDefaultTimestamps && !updatedAtFound { 79 updatedAt, err := attrs.Parse("updated_at:time") 80 if err != nil { 81 return err 82 } 83 opts.Attrs = append(opts.Attrs, updatedAt) 84 } 85 return nil 86 }