更新完善代码生成

This commit is contained in:
xiangheng
2024-04-04 00:57:24 +08:00
parent a75708fe04
commit 2cf673c93c
8 changed files with 130 additions and 36 deletions

View File

@@ -1,6 +1,8 @@
package {{{ .ModuleName }}}
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"x_admin/core/request"
"x_admin/core/response"
@@ -151,12 +153,12 @@ func (hd {{{ title (toCamelCase .ModuleName) }}}Handler) ExportFile(c *gin.Cont
response.FailWithMsg(c, response.SystemError, "查询信息失败")
return
}
f, err := excel.NormalDynamicExport(res, "Sheet1", "用户信息", "", true, false, nil)
f, err := excel.NormalDynamicExport(res, "Sheet1", "{{{ .FunctionName }}}", "", true, false, nil)
if err != nil {
response.FailWithMsg(c, response.SystemError, "导出失败")
return
}
excel.DownLoadExcel("用户信息", c.Writer, f)
excel.DownLoadExcel("{{{ .FunctionName }}}" + time.Now().Format("20060102-150405"), c.Writer, f)
}
// @Summary {{{ .FunctionName }}}导入
@@ -175,9 +177,9 @@ func (hd {{{ title (toCamelCase .ModuleName) }}}Handler) ImportFile(c *gin.Cont
c.String(http.StatusInternalServerError, err.Error())
return
}
for _, t := range importList {
fmt.Printf("%#v", t)
}
// for _, t := range importList {
// fmt.Printf("%#v", t)
// }
err = Service.ImportFile(importList)
response.CheckAndResp(c, err)
}

View File

@@ -16,12 +16,26 @@ import (
请在 admin/entry.go 文件引入{{{ title (toCamelCase .ModuleName) }}}Route注册路由
3. 后台手动添加菜单和按钮
{{{ .ModuleName }}}:add
{{{.ModuleName }}}:edit
{{{.ModuleName }}}:del
{{{.ModuleName }}}:list
{{{.ModuleName }}}:listAll
{{{.ModuleName }}}:detail
admin:{{{ .ModuleName }}}:add
admin:{{{.ModuleName }}}:edit
admin:{{{.ModuleName }}}:del
admin:{{{.ModuleName }}}:list
admin:{{{.ModuleName }}}:listAll
admin:{{{.ModuleName }}}:detail
admin:{{{.ModuleName }}}:ExportFile
admin:{{{.ModuleName }}}:ImportFile
// 列表
INSERT INTO x_system_auth_menu (pid, menu_type, menu_name, paths, component, is_cache, is_show, is_disable, create_time, update_time) VALUES (0, 'C', '{{{ .FunctionName }}}', '/{{{ .ModuleName }}}/index', '{{{ .ModuleName }}}/index', 0, 1, 0, UNIX_TIMESTAMP(), UNIX_TIMESTAMP());
按钮
INSERT INTO x_system_auth_menu (pid, menu_type, menu_name, perms,is_cache, is_show, is_disable, create_time, update_time) VALUES (0, 'A', '{{{ .FunctionName }}}添加','admin:{{{ .ModuleName }}}:add', 0, 1, 0, UNIX_TIMESTAMP(), UNIX_TIMESTAMP());
INSERT INTO x_system_auth_menu (pid, menu_type, menu_name, perms,is_cache, is_show, is_disable, create_time, update_time) VALUES (0, 'A', '{{{ .FunctionName }}}编辑','admin:{{{ .ModuleName }}}:edit', 0, 1, 0, UNIX_TIMESTAMP(), UNIX_TIMESTAMP());
INSERT INTO x_system_auth_menu (pid, menu_type, menu_name, perms,is_cache, is_show, is_disable, create_time, update_time) VALUES (0, 'A', '{{{ .FunctionName }}}删除','admin:{{{ .ModuleName }}}:del', 0, 1, 0, UNIX_TIMESTAMP(), UNIX_TIMESTAMP());
INSERT INTO x_system_auth_menu (pid, menu_type, menu_name, perms,is_cache, is_show, is_disable, create_time, update_time) VALUES (0, 'A', '{{{ .FunctionName }}}列表','admin:{{{ .ModuleName }}}:list', 0, 1, 0, UNIX_TIMESTAMP(), UNIX_TIMESTAMP());
INSERT INTO x_system_auth_menu (pid, menu_type, menu_name, perms,is_cache, is_show, is_disable, create_time, update_time) VALUES (0, 'A', '{{{ .FunctionName }}}全部列表','admin:{{{ .ModuleName }}}:listAll', 0, 1, 0, UNIX_TIMESTAMP(), UNIX_TIMESTAMP());
INSERT INTO x_system_auth_menu (pid, menu_type, menu_name, perms,is_cache, is_show, is_disable, create_time, update_time) VALUES (0, 'A', '{{{ .FunctionName }}}详情','admin:{{{ .ModuleName }}}:detail', 0, 1, 0, UNIX_TIMESTAMP(), UNIX_TIMESTAMP());
INSERT INTO x_system_auth_menu (pid, menu_type, menu_name, perms,is_cache, is_show, is_disable, create_time, update_time) VALUES (0, 'A', '{{{ .FunctionName }}}导出excel','admin:{{{ .ModuleName }}}:ExportFile', 0, 1, 0, UNIX_TIMESTAMP(), UNIX_TIMESTAMP());
INSERT INTO x_system_auth_menu (pid, menu_type, menu_name, perms,is_cache, is_show, is_disable, create_time, update_time) VALUES (0, 'A', '{{{ .FunctionName }}}导入excel','admin:{{{ .ModuleName }}}:ImportFile', 0, 1, 0, UNIX_TIMESTAMP(), UNIX_TIMESTAMP());
*/

View File

@@ -50,7 +50,11 @@ type {{{ title (toCamelCase .EntityName) }}}DelReq struct {
type {{{ title (toCamelCase .EntityName) }}}Resp struct {
{{{- range .Columns }}}
{{{- if or .IsList .IsPk }}}
{{{ title (toCamelCase .GoField) }}} {{{ .GoType }}} `json:"{{{ toCamelCase .GoField }}}" structs:"{{{ toCamelCase .GoField }}}" excel:"name:{{{ .ColumnComment }}};"` // {{{ .ColumnComment }}}
{{{- if .IsPk }}}
{{{ title (toCamelCase .GoField) }}} {{{ .GoType }}} `json:"{{{ toCamelCase .GoField }}}" structs:"{{{ toCamelCase .GoField }}}"` // {{{ .ColumnComment }}}
{{{- else }}}
{{{ title (toCamelCase .GoField) }}} {{{ .GoType }}} `json:"{{{ toCamelCase .GoField }}}" structs:"{{{ toCamelCase .GoField }}}" excel:"name:{{{ .ColumnComment }}};"` // {{{ .ColumnComment }}}
{{{- end }}}
{{{- end }}}
{{{- end }}}
}

View File

@@ -9,15 +9,15 @@ import (
)
type I{{{ title (toCamelCase .EntityName) }}}Service interface {
List(page request.PageReq, listReq {{{ title (toCamelCase .EntityName) }}}ListReq) (res response.PageResp, e error)
ListAll() (res []{{{ title (toCamelCase .EntityName) }}}Resp, e error)
Detail(id int) (res {{{ title (toCamelCase .EntityName) }}}Resp, e error)
Add(addReq {{{ title (toCamelCase .EntityName) }}}AddReq) (e error)
Edit(editReq {{{ title (toCamelCase .EntityName) }}}EditReq) (e error)
Del(id int) (e error)
}
// type I{{{ title (toCamelCase .EntityName) }}}Service interface {
// List(page request.PageReq, listReq {{{ title (toCamelCase .EntityName) }}}ListReq) (res response.PageResp, e error)
// ListAll() (res []{{{ title (toCamelCase .EntityName) }}}Resp, e error)
//
// Detail(id int) (res {{{ title (toCamelCase .EntityName) }}}Resp, e error)
// Add(addReq {{{ title (toCamelCase .EntityName) }}}AddReq) (e error)
// Edit(editReq {{{ title (toCamelCase .EntityName) }}}EditReq) (e error)
// Del(id int) (e error)
// }
var Service=New{{{ title (toCamelCase .EntityName) }}}Service()
//New{{{ title (toCamelCase .EntityName) }}}Service 初始化
func New{{{ title (toCamelCase .EntityName) }}}Service() *{{{ toCamelCase .EntityName }}}Service {

View File

@@ -1,4 +1,8 @@
import request from '@/utils/request'
import config from '@/config'
import queryString from 'query-string'
import { getToken } from '@/utils/auth'
// {{{.FunctionName}}}列表
export function {{{.ModuleName}}}_list(params?: Record<string, any>) {
@@ -28,3 +32,11 @@ export function {{{.ModuleName}}}_edit(params: Record<string, any>) {
export function {{{.ModuleName}}}_delete(params: Record<string, any>) {
return request.post({ url: '/{{{.ModuleName}}}/del', params })
}
// {{{.FunctionName}}}导入
export const {{{.ModuleName}}}_import_file = '/{{{.ModuleName}}}/ImportFile'
// {{{.FunctionName}}}导出
export function {{{.ModuleName}}}_export_file(params: any) {
return (window.location.href =`${config.baseUrl}${config.urlPrefix}/{{{.ModuleName}}}/ExportFile?token=${getToken()}&` + queryString.stringify(params))
}

View File

@@ -51,6 +51,27 @@
</template>
新增
</el-button>
<upload
class="ml-3 mr-3"
:url="{{{.ModuleName}}}_export_file"
:data="{ cid: 0 }"
type="file"
:show-progress="true"
@change="resetPage"
>
<el-button type="primary">
<template #icon>
<icon name="el-icon-Upload" />
</template>
导入
</el-button>
</upload>
<el-button type="primary" @click="exportFile">
<template #icon>
<icon name="el-icon-Download" />
</template>
导出
</el-button>
</div>
<el-table
class="mt-4"
@@ -121,7 +142,7 @@
</div>
</template>
<script lang="ts" setup>
import { {{{ .ModuleName }}}_delete, {{{ .ModuleName }}}_list } from '@/api/{{{ .ModuleName }}}'
import { {{{ .ModuleName }}}_delete, {{{ .ModuleName }}}_list,{{{.ModuleName}}}_import_file, {{{.ModuleName}}}_export_file } from '@/api/{{{ .ModuleName }}}'
{{{- if ge (len .DictFields) 1 }}}
import { useDictData } from '@/hooks/useDictOptions'
{{{- end }}}
@@ -168,18 +189,27 @@ const handleAdd = async () => {
}
const handleEdit = async (data: any) => {
showEdit.value = true
await nextTick()
editRef.value?.open('edit')
editRef.value?.getDetail(data)
try {
showEdit.value = true
await nextTick()
editRef.value?.open('edit')
editRef.value?.getDetail(data)
} catch (error) {}
}
const handleDelete = async ({{{ .PrimaryKey }}}: number) => {
await feedback.confirm('确定要删除?')
await {{{ .ModuleName }}}_delete({ {{{ .PrimaryKey }}} })
feedback.msgSuccess('删除成功')
getLists()
try {
await feedback.confirm('确定要删除?')
await {{{ .ModuleName }}}_delete({ {{{ .PrimaryKey }}} })
feedback.msgSuccess('删除成功')
getLists()
} catch (error) {}
}
const exportFile = async () => {
try {
await feedback.confirm('确定要导出?')
await {{{.ModuleName}}}_export_file(queryParams)
} catch (error) {}
}
getLists()
</script>

View File

@@ -7,6 +7,7 @@ import (
"x_admin/core"
"github.com/gin-gonic/gin"
"github.com/go-sql-driver/mysql"
"github.com/jinzhu/copier"
"go.uber.org/zap"
"gorm.io/gorm"
@@ -193,7 +194,25 @@ func CheckErr(err error, template string, args ...interface{}) (e error) {
args = append(args, err)
if err != nil {
core.Logger.WithOptions(zap.AddCallerSkip(1)).Errorf(template+prefix+"err=[%+v]", args...)
return SystemError
return SystemError.Make(template)
}
return
}
// 插入操作违反唯一约束时,会发生此错误:
func CheckMysqlErr(err error) (e error) {
if mysqlErr, ok := err.(*mysql.MySQLError); ok {
switch mysqlErr.Number {
case 404:
core.Logger.WithOptions(zap.AddCallerSkip(1)).Errorf("record not found: err=[%+v]", err)
return SystemError.Make("record not found")
case 1062: // MySQL中表示重复条目的代码
core.Logger.WithOptions(zap.AddCallerSkip(1)).Infof("数据已存在: err=[%+v]", err)
return SystemError.Make("数据已存在")
default:
// 处理其他错误
core.Logger.WithOptions(zap.AddCallerSkip(1)).Errorf("未知错误: err=[%+v]", err)
}
}
return
}
@@ -201,8 +220,8 @@ func CheckErr(err error, template string, args ...interface{}) (e error) {
// CheckErrDBNotRecord 校验数据库记录不存在的错误
func CheckErrDBNotRecord(err error, msg string) (e error) {
if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
core.Logger.WithOptions(zap.AddCallerSkip(1)).Infof("CheckErrDBNotRecord err: err=[%+v]", err)
return AssertArgumentError.Make(msg)
core.Logger.WithOptions(zap.AddCallerSkip(1)).Infof("记录不存在: err=[%+v]", err)
return SystemError.Make(msg)
}
return
}

View File

@@ -19,7 +19,7 @@ import (
var trans ut.Translator
// loca 通常取决于 http 请求头的 'Accept-Language'
// local 通常取决于 http 请求头的 'Accept-Language'
func transInit(local string) (err error) {
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
zhT := zh.New() //chinese
@@ -58,7 +58,8 @@ var VerifyUtil = verifyUtil{}
type verifyUtil struct{}
func (vu verifyUtil) VerifyJSON(c *gin.Context, obj any) (e error) {
if err := c.ShouldBindBodyWith(obj, binding.JSON); err != nil {
// var reqInfo interface{}
if err := c.ShouldBindBodyWith(&obj, binding.JSON); err != nil {
errs, ok := err.(validator.ValidationErrors)
if !ok {
e = response.ParamsValidError.MakeData(err.Error())
@@ -67,7 +68,19 @@ func (vu verifyUtil) VerifyJSON(c *gin.Context, obj any) (e error) {
e = response.ParamsValidError.MakeData(errs.Translate(trans))
return
}
// response.Copy(obj, reqInfo)
return
// if err := c.ShouldBindBodyWith(obj, binding.JSON); err != nil {
// errs, ok := err.(validator.ValidationErrors)
// if !ok {
// e = response.ParamsValidError.MakeData(err.Error())
// return
// }
// e = response.ParamsValidError.MakeData(errs.Translate(trans))
// return
// }
// return
}
func (vu verifyUtil) VerifyJSONArray(c *gin.Context, obj any) (e error) {