From 4466482ad98a3faec0f2df9599b51924930731d1 Mon Sep 17 00:00:00 2001 From: zhangwenjian Date: Wed, 9 Sep 2020 22:43:21 +0800 Subject: [PATCH] feat:update gen --- app/admin/apis/tools/gen.go | 67 +++++++++-- app/admin/models/tools/systables.go | 3 + app/admin/router/initrouter.go | 6 +- app/admin/router/sysjob.go | 35 ++++++ app/admin/router/sysrouter.go | 24 ---- app/admin/service/dto/sysjob.go | 4 +- template/v1.2/dto.go.template | 117 ++++++++++++++++++++ template/v1.2/model.go.template | 46 ++++++++ template/v1.2/routercheckrole.go.template | 32 ++++++ template/v1.2/routernocheckrole.go.template | 23 ++++ 10 files changed, 322 insertions(+), 35 deletions(-) create mode 100644 app/admin/router/sysjob.go create mode 100644 template/v1.2/dto.go.template create mode 100644 template/v1.2/model.go.template create mode 100644 template/v1.2/routercheckrole.go.template create mode 100644 template/v1.2/routernocheckrole.go.template diff --git a/app/admin/apis/tools/gen.go b/app/admin/apis/tools/gen.go index b3a1e73..4de3a4a 100644 --- a/app/admin/apis/tools/gen.go +++ b/app/admin/apis/tools/gen.go @@ -65,21 +65,14 @@ func GenCode(c *gin.Context) { tools2.HasError(err, "", -1) table.TableId = id tab, _ := table.Get() - ischeckrole := true routerfile := "template/routercheckrole.go.template" - if c.Request.FormValue("ischeckrole") != "" { - ischeckrole, err = tools2.StringToBool(c.Request.FormValue("ischeckrole")) - if err != nil { - ischeckrole = true - } - } oldTest := "// {{认证路由自动补充在此处请勿删除}}" newText := "// {{认证路由自动补充在此处请勿删除}} \r\n register" + tab.ClassName + "Router(v1,authMiddleware)" - if !ischeckrole { + if !tab.IsAuth { oldTest = "// {{无需认证路由自动补充在此处请勿删除}}" newText = "// {{无需认证路由自动补充在此处请勿删除}} \r\n register" + tab.ClassName + "Router(v1)" routerfile = "template/routernocheckrole.go.template" @@ -143,6 +136,64 @@ func GenCode(c *gin.Context) { app.OK(c, "", "Code generated successfully!") } + +func GenCodeV2(c *gin.Context) { + table := tools.SysTables{} + id, err := tools2.StringToInt(c.Param("tableId")) + tools2.HasError(err, "", -1) + table.TableId = id + tab, _ := table.Get() + + routerfile := "template/v1.2/routercheckrole.go.template" + + + if !tab.IsAuth { + routerfile = "template/v1.2/routernocheckrole.go.template" + } + + t1, err := template.ParseFiles("template/v1.2/model.go.template") + tools2.HasError(err, "", -1) + t2, err := template.ParseFiles("template/api.go.template") + tools2.HasError(err, "", -1) + t3, err := template.ParseFiles(routerfile) + tools2.HasError(err, "", -1) + t4, err := template.ParseFiles("template/js.go.template") + tools2.HasError(err, "", -1) + t5, err := template.ParseFiles("template/vue.go.template") + tools2.HasError(err, "", -1) + t6, err := template.ParseFiles("template/v1.2/dto.go.template") + tools2.HasError(err, "", -1) + + _ = tools2.PathCreate("./app/admin/apis/" + tab.ModuleName + "/") + _ = tools2.PathCreate("./app/admin/models/") + _ = tools2.PathCreate("./app/admin/router/") + _ = tools2.PathCreate("./app/admin/dto/") + _ = tools2.PathCreate(config.GenConfig.FrontPath + "/api/") + _ = tools2.PathCreate(config.GenConfig.FrontPath + "/views/" + tab.PackageName) + + var b1 bytes.Buffer + err = t1.Execute(&b1, tab) + var b2 bytes.Buffer + err = t2.Execute(&b2, tab) + var b3 bytes.Buffer + err = t3.Execute(&b3, tab) + var b4 bytes.Buffer + err = t4.Execute(&b4, tab) + var b5 bytes.Buffer + err = t5.Execute(&b5, tab) + var b6 bytes.Buffer + err = t6.Execute(&b6, tab) + tools2.FileCreate(b1, "./app/admin/models/"+tab.PackageName+".go") + tools2.FileCreate(b2, "./app/admin/apis/"+tab.ModuleName+"/"+tab.PackageName+".go") + tools2.FileCreate(b3, "./app/admin/router/"+tab.PackageName+".go") + tools2.FileCreate(b4, config.GenConfig.FrontPath+"/api/"+tab.PackageName+".js") + tools2.FileCreate(b5, config.GenConfig.FrontPath+"/views/"+tab.PackageName+"/index.vue") + tools2.FileCreate(b6, "./app/admin/service/dto/"+tab.PackageName+".go") + + + app.OK(c, "", "Code generated successfully!") +} + func GenMenuAndApi(c *gin.Context) { table := tools.SysTables{} diff --git a/app/admin/models/tools/systables.go b/app/admin/models/tools/systables.go index 24f973b..d3cb040 100644 --- a/app/admin/models/tools/systables.go +++ b/app/admin/models/tools/systables.go @@ -28,6 +28,9 @@ type SysTables struct { Tree bool `gorm:"size:1;" json:"tree"` Crud bool `gorm:"size:1;" json:"crud"` Remark string `gorm:"size:255;" json:"remark"` + IsDataScope bool `gorm:"size:1;" json:"isDataScope"` + IsActions bool `gorm:"size:1;" json:"isActions"` + IsAuth bool `gorm:"size:1;" json:"isAuth"` IsLogicalDelete string `gorm:"size:1;" json:"isLogicalDelete"` LogicalDelete bool `gorm:"size:1;" json:"logicalDelete"` LogicalDeleteColumn string `gorm:"size:128;" json:"logicalDeleteColumn"` diff --git a/app/admin/router/initrouter.go b/app/admin/router/initrouter.go index e6411da..d0c5b58 100644 --- a/app/admin/router/initrouter.go +++ b/app/admin/router/initrouter.go @@ -5,12 +5,15 @@ import ( "go-admin/app/admin/middleware" "go-admin/app/admin/middleware/handler" "go-admin/common/global" + jwt "go-admin/pkg/jwtauth" _ "go-admin/pkg/jwtauth" "go-admin/tools" config2 "go-admin/tools/config" "gorm.io/gorm" ) +var authMiddleware = new(jwt.GinJWTMiddleware) + func InitRouter() *gin.Engine { var r *gin.Engine if global.GinEngine == nil { @@ -24,7 +27,8 @@ func InitRouter() *gin.Engine { r.Use(middleware.WithContextDb(map[string]*gorm.DB{"*": global.Eloquent})) middleware.InitMiddleware(r) // the jwt middleware - authMiddleware, err := middleware.AuthInit() + var err error + authMiddleware, err = middleware.AuthInit() tools.HasError(err, "JWT Init Error", 500) // 注册系统路由 diff --git a/app/admin/router/sysjob.go b/app/admin/router/sysjob.go new file mode 100644 index 0000000..3d7c015 --- /dev/null +++ b/app/admin/router/sysjob.go @@ -0,0 +1,35 @@ +package router + +import ( + "github.com/gin-gonic/gin" + "go-admin/app/admin/apis/sysjob" + "go-admin/app/admin/middleware" + "go-admin/app/admin/models" + "go-admin/app/admin/service/dto" + "go-admin/common/actions" + jwt "go-admin/pkg/jwtauth" +) + +func init() { + routerCheckRole = append(routerCheckRole, registerSysJobRouter) +} + +// 需认证的路由代码 +func registerSysJobRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) { + + r := v1.Group("/sysjob").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()) + { + sysJob := &models.SysJob{} + r.GET("", actions.PermissionAction(), actions.IndexAction(sysJob, new(dto.SysJobSearch), func() interface{} { + list := make([]models.SysJob, 0) + return &list + })) + r.GET("/:id", actions.PermissionAction(), actions.ViewAction(new(dto.SysJobById))) + r.POST("", actions.CreateAction(new(dto.SysJobControl))) + r.PUT("", actions.PermissionAction(), actions.UpdateAction(new(dto.SysJobControl))) + r.DELETE("/:id", actions.PermissionAction(), actions.DeleteAction(new(dto.SysJobById))) + } + + v1.GET("/job/remove/:jobId", sysjob.RemoveJob) + v1.GET("/job/start/:jobId", sysjob.StartJob) +} diff --git a/app/admin/router/sysrouter.go b/app/admin/router/sysrouter.go index c2f9f35..60776a8 100644 --- a/app/admin/router/sysrouter.go +++ b/app/admin/router/sysrouter.go @@ -6,15 +6,11 @@ import ( log2 "go-admin/app/admin/apis/log" "go-admin/app/admin/apis/monitor" "go-admin/app/admin/apis/public" - "go-admin/app/admin/apis/sysjob" "go-admin/app/admin/apis/system" "go-admin/app/admin/apis/system/dict" . "go-admin/app/admin/apis/tools" "go-admin/app/admin/middleware" "go-admin/app/admin/middleware/handler" - "go-admin/app/admin/models" - "go-admin/app/admin/service/dto" - "go-admin/common/actions" _ "go-admin/docs" jwt "go-admin/pkg/jwtauth" "go-admin/pkg/ws" @@ -108,25 +104,6 @@ func registerSysTableRouter(v1 *gin.RouterGroup) { } } -func registerSysJobRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) { - - r := v1.Group("/sysjob").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()) - { - sysJob := &models.SysJob{} - r.GET("", actions.PermissionAction(), actions.IndexAction(sysJob, new(dto.SysJobSearch), func() interface{} { - list := make([]models.SysJob, 0) - return &list - })) - r.GET("/:id", actions.PermissionAction(), actions.ViewAction(new(dto.SysJobById))) - r.POST("", actions.CreateAction(new(dto.SysJobControl))) - r.PUT("", actions.PermissionAction(), actions.UpdateAction(new(dto.SysJobControl))) - r.DELETE("/:id", actions.PermissionAction(), actions.DeleteAction(new(dto.SysJobById))) - } - - v1.GET("/job/remove/:jobId", sysjob.RemoveJob) - v1.GET("/job/start/:jobId", sysjob.StartJob) -} - func sysCheckRoleRouterInit(r *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) { r.POST("/login", authMiddleware.LoginHandler) // Refresh time can be longer than token timeout @@ -150,7 +127,6 @@ func sysCheckRoleRouterInit(r *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddle registerMenuRouter(v1, authMiddleware) registerLoginLogRouter(v1, authMiddleware) registerOperLogRouter(v1, authMiddleware) - registerSysJobRouter(v1, authMiddleware) } func registerBaseRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) { diff --git a/app/admin/service/dto/sysjob.go b/app/admin/service/dto/sysjob.go index c291bd5..f69b41e 100644 --- a/app/admin/service/dto/sysjob.go +++ b/app/admin/service/dto/sysjob.go @@ -47,10 +47,10 @@ type SysJobControl struct { CronExpression string `json:"cronExpression"` // cron表达式 InvokeTarget string `json:"invokeTarget"` // 调用目标 Args string `json:"args"` // 目标参数 - MisfirePolicy int `json:"misfirePolicy"` // 执行策略 + MisfirePolicy int `json:"misfirePolicy"` // 执行策略 Concurrent int `json:"concurrent"` // 是否并发 Status int `json:"status"` // 状态 - EntryId int `json:"entry_id"` // job启动时返回的id + EntryId int `json:"entryId"` // job启动时返回的id } func (s *SysJobControl) Bind(ctx *gin.Context) error { diff --git a/template/v1.2/dto.go.template b/template/v1.2/dto.go.template new file mode 100644 index 0000000..7354046 --- /dev/null +++ b/template/v1.2/dto.go.template @@ -0,0 +1,117 @@ +package dto + +import ( + "github.com/gin-gonic/gin" + "go-admin/app/admin/models" + "go-admin/common/dto" + models2 "go-admin/common/models" + "net/http" +) + +type {{.ClassName}}Search struct { + Pagination `search:"-"` + {{ $tablename := .TBName -}} + {{ range .Columns -}} + {{$z := .IsQuery}} + {{- if ($z) -}} + {{.GoField}} {{.GoType}} `form:"{{.JsonField}}" search:"type:{{if eq .QueryType "EQ"}}exact{{ else if eq .QueryType "NE"}}iexact{{ else if eq .QueryType "LIKE"}}contains{{ else if eq .QueryType "GT"}}gt{{ else if eq .QueryType "GTE"}}gte{{ else if eq .QueryType "LT"}}lt{{ else if eq .QueryType "LTE"}}lte{{- end }};column:{{.ColumnName}};table:{{$tablename}}"` // {{.ColumnComment}} + + {{end -}} + {{- end }} +} + +func (m *{{.ClassName}}Search) GetNeedSearch() interface{} { + return *m +} + +func (m *{{.ClassName}}Search) Bind(ctx *gin.Context) error { + return ctx.Bind(m) +} + +func (m *{{.ClassName}}Search) Generate() dto.Index { + o := *m + return &o +} + +func (m *{{.ClassName}}Search) GetPageIndex() int { + return m.PageIndex +} + +func (m *{{.ClassName}}Search) GetPageSize() int { + return m.PageSize +} + +type {{.ClassName}}Control struct { + {{ range .Columns -}} + {{$x := .Pk}} + {{- if ($x) }} + {{.GoField}} {{.GoType}} `json:"{{.JsonField}}""` // {{.ColumnComment}} + {{- else if eq .GoField "CreatedAt" -}} + {{- else if eq .GoField "UpdatedAt" -}} + {{- else if eq .GoField "DeletedAt" -}} + {{- else }} + {{.GoField}} {{.GoType}} `json:"{{.JsonField}}""` // {{.ColumnComment}}{{end -}} + {{- end }} +} + +func (s *{{.ClassName}}Control) Bind(ctx *gin.Context) error { + return ctx.Bind(s) +} + +func (s *{{.ClassName}}Control) Generate() dto.Control { + cp := *s + return &cp +} + +func (s *{{.ClassName}}Control) GenerateM() (models2.ActiveRecord, error) { + return &models.{{.ClassName}}{ + {{ range .Columns -}} + {{$x := .Pk}} + {{- if ($x) }} + {{.GoField}}: s.{{.GoField}}, + {{- else if eq .GoField "CreatedAt" -}} + {{- else if eq .GoField "UpdatedAt" -}} + {{- else if eq .GoField "DeletedAt" -}} + {{- else }} + {{.GoField}}: s.{{.GoField}}, + {{- end }} + }, nil +} + +func (s *{{.ClassName}}Control) GetId() interface{} { + return s.{{.PkColumn}} +} + +type {{.ClassName}}ById struct { + Id int `uri:"id" validate:"required"` + Ids []int `json:"ids"` +} + +func (s *{{.ClassName}}ById) Bind(ctx *gin.Context) error { + if ctx.Request.Method == http.MethodDelete { + err := ctx.Bind(s) + if err != nil { + return err + } + if len(s.Ids) > 0 { + return nil + } + } + return ctx.BindUri(s) +} + +func (s *{{.ClassName}}ById) Generate() dto.Control { + cp := *s + return &cp +} + +func (s *{{.ClassName}}ById) GenerateM() (models2.ActiveRecord, error) { + return &models.{{.ClassName}}{}, nil +} + +func (s *{{.ClassName}}ById) GetId() interface{} { + if len(s.Ids) > 0 { + return s.Ids + } + return s.Id +} diff --git a/template/v1.2/model.go.template b/template/v1.2/model.go.template new file mode 100644 index 0000000..b1359b8 --- /dev/null +++ b/template/v1.2/model.go.template @@ -0,0 +1,46 @@ +package models + +import ( + "go-admin/common/dto" + orm "go-admin/common/global" + "go-admin/common/models" + "go-admin/tools" + "strconv" +) + +type SysJob struct { + {{ range .Columns -}} + {{$x := .Pk}} + {{- if ($x) }} + {{.GoField}} {{.GoType}} `json:"{{.JsonField}}" gorm:"type:{{.ColumnType}};primary_key;AUTO_INCREMENT;comment:{{.ColumnComment}}"` // {{.ColumnComment}} + {{- else if eq .GoField "CreatedAt" -}} + {{- else if eq .GoField "UpdatedAt" -}} + {{- else if eq .GoField "DeletedAt" -}} + {{- else }} + {{.GoField}} {{.GoType}} `json:"{{.JsonField}}" gorm:"type:{{.ColumnType}};comment:{{.ColumnComment}}"` // {{.ColumnComment}}{{end -}} + {{- end }} + DataScope string `json:"dataScope" gorm:"-"` + Params string `json:"params" gorm:"-"` + BaseModel +} + +func ({{.ClassName}}) TableName() string { + return "{{.TBName}}" +} + +func (e *{{.ClassName}}) Generate() models.ActiveRecord { + o := *e + return &o +} + +func (e *{{.ClassName}}) GetId() interface{} { + return e.{{.PkColumn}} +} + +func (e *{{.ClassName}}) SetCreateBy(createBy uint) { + e.CreateBy = strconv.Itoa(int(createBy)) +} + +func (e *{{.ClassName}}) SetUpdateBy(updateBy uint) { + e.UpdateBy = strconv.Itoa(int(updateBy)) +} \ No newline at end of file diff --git a/template/v1.2/routercheckrole.go.template b/template/v1.2/routercheckrole.go.template new file mode 100644 index 0000000..7d153f7 --- /dev/null +++ b/template/v1.2/routercheckrole.go.template @@ -0,0 +1,32 @@ +package router + +import ( + "github.com/gin-gonic/gin" + + "go-admin/apis/{{.ModuleName}}" + "go-admin/app/admin/middleware" + "go-admin/app/admin/models" + "go-admin/app/admin/service/dto" + "go-admin/common/actions" + jwt "go-admin/pkg/jwtauth" +) + +func init() { + routerCheckRole = append(routerCheckRole, register{{.ClassName}}Router) +} + +// 需认证的路由代码 +func register{{.ClassName}}Router(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) { + r := v1.Group("/{{.ModuleName}}").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()) + { + model := &models.{{.ClassName}}{} + r.GET("", actions.PermissionAction(), actions.IndexAction(model, new(dto.{{.ClassName}}Search), func() interface{} { + list := make([]models.{{.ClassName}}, 0) + return &list + })) + r.GET("/:id", actions.PermissionAction(), actions.ViewAction(new(dto.{{.ClassName}}ById))) + r.POST("", actions.CreateAction(new(dto.{{.ClassName}}Control))) + r.PUT("", actions.PermissionAction(), actions.UpdateAction(new(dto.{{.ClassName}}Control))) + r.DELETE("/:id", actions.PermissionAction(), actions.DeleteAction(new(dto.{{.ClassName}}ById))) + } +} diff --git a/template/v1.2/routernocheckrole.go.template b/template/v1.2/routernocheckrole.go.template new file mode 100644 index 0000000..c42ac94 --- /dev/null +++ b/template/v1.2/routernocheckrole.go.template @@ -0,0 +1,23 @@ +package router + +import ( + "github.com/gin-gonic/gin" + + "go-admin/apis/{{.ModuleName}}" +) + +// 无需认证的路由代码 +func register{{.ClassName}}Router(v1 *gin.RouterGroup) { + r := v1.Group("/{{.ModuleName}}") + { + model := &models.{{.ClassName}}{} + r.GET("", actions.IndexAction(model, new(dto.{{.ClassName}}Search), func() interface{} { + list := make([]models.{{.ClassName}}, 0) + return &list + })) + r.GET("/:id", actions.ViewAction(new(dto.{{.ClassName}}ById))) + r.POST("", actions.CreateAction(new(dto.{{.ClassName}}Control))) + r.PUT("", actions.UpdateAction(new(dto.{{.ClassName}}Control))) + r.DELETE("/:id", actions.DeleteAction(new(dto.{{.ClassName}}ById))) + } +}