feat:update gen

This commit is contained in:
zhangwenjian
2020-09-09 22:43:21 +08:00
parent 3bd3656d15
commit 4466482ad9
10 changed files with 322 additions and 35 deletions
+59 -8
View File
@@ -65,21 +65,14 @@ func GenCode(c *gin.Context) {
tools2.HasError(err, "", -1) tools2.HasError(err, "", -1)
table.TableId = id table.TableId = id
tab, _ := table.Get() tab, _ := table.Get()
ischeckrole := true
routerfile := "template/routercheckrole.go.template" routerfile := "template/routercheckrole.go.template"
if c.Request.FormValue("ischeckrole") != "" {
ischeckrole, err = tools2.StringToBool(c.Request.FormValue("ischeckrole"))
if err != nil {
ischeckrole = true
}
}
oldTest := "// {{认证路由自动补充在此处请勿删除}}" oldTest := "// {{认证路由自动补充在此处请勿删除}}"
newText := "// {{认证路由自动补充在此处请勿删除}} \r\n register" + tab.ClassName + "Router(v1,authMiddleware)" newText := "// {{认证路由自动补充在此处请勿删除}} \r\n register" + tab.ClassName + "Router(v1,authMiddleware)"
if !ischeckrole { if !tab.IsAuth {
oldTest = "// {{无需认证路由自动补充在此处请勿删除}}" oldTest = "// {{无需认证路由自动补充在此处请勿删除}}"
newText = "// {{无需认证路由自动补充在此处请勿删除}} \r\n register" + tab.ClassName + "Router(v1)" newText = "// {{无需认证路由自动补充在此处请勿删除}} \r\n register" + tab.ClassName + "Router(v1)"
routerfile = "template/routernocheckrole.go.template" routerfile = "template/routernocheckrole.go.template"
@@ -143,6 +136,64 @@ func GenCode(c *gin.Context) {
app.OK(c, "", "Code generated successfully") 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) { func GenMenuAndApi(c *gin.Context) {
table := tools.SysTables{} table := tools.SysTables{}
+3
View File
@@ -28,6 +28,9 @@ type SysTables struct {
Tree bool `gorm:"size:1;" json:"tree"` Tree bool `gorm:"size:1;" json:"tree"`
Crud bool `gorm:"size:1;" json:"crud"` Crud bool `gorm:"size:1;" json:"crud"`
Remark string `gorm:"size:255;" json:"remark"` 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"` IsLogicalDelete string `gorm:"size:1;" json:"isLogicalDelete"`
LogicalDelete bool `gorm:"size:1;" json:"logicalDelete"` LogicalDelete bool `gorm:"size:1;" json:"logicalDelete"`
LogicalDeleteColumn string `gorm:"size:128;" json:"logicalDeleteColumn"` LogicalDeleteColumn string `gorm:"size:128;" json:"logicalDeleteColumn"`
+5 -1
View File
@@ -5,12 +5,15 @@ import (
"go-admin/app/admin/middleware" "go-admin/app/admin/middleware"
"go-admin/app/admin/middleware/handler" "go-admin/app/admin/middleware/handler"
"go-admin/common/global" "go-admin/common/global"
jwt "go-admin/pkg/jwtauth"
_ "go-admin/pkg/jwtauth" _ "go-admin/pkg/jwtauth"
"go-admin/tools" "go-admin/tools"
config2 "go-admin/tools/config" config2 "go-admin/tools/config"
"gorm.io/gorm" "gorm.io/gorm"
) )
var authMiddleware = new(jwt.GinJWTMiddleware)
func InitRouter() *gin.Engine { func InitRouter() *gin.Engine {
var r *gin.Engine var r *gin.Engine
if global.GinEngine == nil { if global.GinEngine == nil {
@@ -24,7 +27,8 @@ func InitRouter() *gin.Engine {
r.Use(middleware.WithContextDb(map[string]*gorm.DB{"*": global.Eloquent})) r.Use(middleware.WithContextDb(map[string]*gorm.DB{"*": global.Eloquent}))
middleware.InitMiddleware(r) middleware.InitMiddleware(r)
// the jwt middleware // the jwt middleware
authMiddleware, err := middleware.AuthInit() var err error
authMiddleware, err = middleware.AuthInit()
tools.HasError(err, "JWT Init Error", 500) tools.HasError(err, "JWT Init Error", 500)
// 注册系统路由 // 注册系统路由
+35
View File
@@ -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)
}
-24
View File
@@ -6,15 +6,11 @@ import (
log2 "go-admin/app/admin/apis/log" log2 "go-admin/app/admin/apis/log"
"go-admin/app/admin/apis/monitor" "go-admin/app/admin/apis/monitor"
"go-admin/app/admin/apis/public" "go-admin/app/admin/apis/public"
"go-admin/app/admin/apis/sysjob"
"go-admin/app/admin/apis/system" "go-admin/app/admin/apis/system"
"go-admin/app/admin/apis/system/dict" "go-admin/app/admin/apis/system/dict"
. "go-admin/app/admin/apis/tools" . "go-admin/app/admin/apis/tools"
"go-admin/app/admin/middleware" "go-admin/app/admin/middleware"
"go-admin/app/admin/middleware/handler" "go-admin/app/admin/middleware/handler"
"go-admin/app/admin/models"
"go-admin/app/admin/service/dto"
"go-admin/common/actions"
_ "go-admin/docs" _ "go-admin/docs"
jwt "go-admin/pkg/jwtauth" jwt "go-admin/pkg/jwtauth"
"go-admin/pkg/ws" "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) { func sysCheckRoleRouterInit(r *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
r.POST("/login", authMiddleware.LoginHandler) r.POST("/login", authMiddleware.LoginHandler)
// Refresh time can be longer than token timeout // Refresh time can be longer than token timeout
@@ -150,7 +127,6 @@ func sysCheckRoleRouterInit(r *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddle
registerMenuRouter(v1, authMiddleware) registerMenuRouter(v1, authMiddleware)
registerLoginLogRouter(v1, authMiddleware) registerLoginLogRouter(v1, authMiddleware)
registerOperLogRouter(v1, authMiddleware) registerOperLogRouter(v1, authMiddleware)
registerSysJobRouter(v1, authMiddleware)
} }
func registerBaseRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) { func registerBaseRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
+2 -2
View File
@@ -47,10 +47,10 @@ type SysJobControl struct {
CronExpression string `json:"cronExpression"` // cron表达式 CronExpression string `json:"cronExpression"` // cron表达式
InvokeTarget string `json:"invokeTarget"` // 调用目标 InvokeTarget string `json:"invokeTarget"` // 调用目标
Args string `json:"args"` // 目标参数 Args string `json:"args"` // 目标参数
MisfirePolicy int `json:"misfirePolicy"` // 执行策略 MisfirePolicy int `json:"misfirePolicy"` // 执行策略
Concurrent int `json:"concurrent"` // 是否并发 Concurrent int `json:"concurrent"` // 是否并发
Status int `json:"status"` // 状态 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 { func (s *SysJobControl) Bind(ctx *gin.Context) error {
+117
View File
@@ -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
}
+46
View File
@@ -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))
}
+32
View File
@@ -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)))
}
}
@@ -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)))
}
}