Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions .claude/skills/new-business-module/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,17 @@ description: Scaffold a new single-table CRUD business module end to end — mig

### 3. 生成 model / dto / router 三个文件(Actions 模式)

不要手写 Api 与 Service。使用 `common/actions` 的通用 Action,一个模块只需
model、dto、router 三个文件,完整写法照抄 `app/demo/` 的结构。
不要手写 Api 与 Service。使用 `common/actions` 的泛型 Action
(`actions.Index[Model, Search]()` 等),一个模块只需 model、dto、router
三个文件,完整写法照抄 `app/demo/` 的结构。

**关键正确性要求**(这三条是实际出问题最多的地方):
**关键正确性要求**:

- Model 实现 `models.ActiveRecord`(`Generate` / `GetId` / `TableName`),
`TableName()` 必须显式声明——GORM 配置了 `SingularTable`,不会自动推导
- **`Generate()` 必须返回副本,不要就地返回**——Action 在并发请求间复用实例,
就地返回会导致请求之间串数据;这个问题单人测试时几乎不出现,上线后才暴露
- `TableName()` 必须显式声明——GORM 配置了 `SingularTable`,不会自动推导
- 增改 DTO 写 `ToModel() (*Model, error)`;模型与 DTO 配错会编译不过
- **不要写 `Generate()`**,也不要用旧的 `IndexAction` 等五个(已 Deprecated):
旧写法在并发请求间复用实例,`Generate()` 一旦就地返回就会串数据,
单人测试时几乎不出现、上线后才暴露;泛型 Action 每个请求新建自己的值
- 完成后确认 `cmd/api/` 中已用 `_` 导入新包,否则路由不会被注册

### 4. 写菜单、接口与权限种子数据
Expand Down Expand Up @@ -82,7 +84,7 @@ model、dto、router 三个文件,完整写法照抄 `app/demo/` 的结构。

| 检查项 | 出错后果 |
| --- | --- |
| `Generate()` 是否返回副本 | 并发请求之间串数据 |
| 路由是否用泛型 Action 而非旧的 `IndexAction` 等 | 旧写法要靠 `Generate()` 返回副本,漏了就并发串数据 |
| 是否使用 `e.Orm` 而非全局 DB | 多租户下拿到错误的数据库连接 |
| `TableName()` 是否显式声明 | GORM 不会自动推导 |
| 迁移文件是否放在 `version/` | 放进 `version-local/` 会被忽略,别人拉代码看不到 |
Expand Down
34 changes: 17 additions & 17 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,34 +20,34 @@ Router → Api → Service → Model

## 优先使用通用 Action

单表 CRUD **不要手写 Api 与 Service**。`common/actions` 提供的五个
Action 已覆盖参数绑定、数据权限过滤、操作人注入、分页与错误响应:
单表 CRUD **不要手写 Api 与 Service**。`common/actions` 提供的泛型 Action
已覆盖参数绑定、数据权限过滤、操作人注入、分页与错误响应:

```go
r := v1.Group("/demo-product").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
m := &models.DemoProduct{}
r.GET("", actions.PermissionAction(), actions.IndexAction(m, new(dto.DemoProductSearch), func() interface{} {
list := make([]models.DemoProduct, 0); return &list
}))
r.GET("/:id", actions.PermissionAction(), actions.ViewAction(new(dto.DemoProductById), func() interface{} {
return &models.DemoProduct{}
}))
r.POST("", actions.CreateAction(new(dto.DemoProductControl)))
r.PUT("/:id", actions.PermissionAction(), actions.UpdateAction(new(dto.DemoProductControl)))
r.DELETE("", actions.PermissionAction(), actions.DeleteAction(new(dto.DemoProductById)))
r.GET("", actions.PermissionAction(), actions.Index[models.DemoProduct, dto.DemoProductSearch]())
r.GET("/:id", actions.PermissionAction(), actions.View[models.DemoProduct, dto.DemoProductById]())
r.POST("", actions.Create[models.DemoProduct, dto.DemoProductControl]())
r.PUT("/:id", actions.PermissionAction(), actions.Update[models.DemoProduct, dto.DemoProductControl]())
r.DELETE("", actions.PermissionAction(), actions.Delete[models.DemoProduct, dto.DemoProductById]())
}
```

这样一个模块只需 **model + dto + router** 三个文件,完整示例见 `app/demo/`。

使用通用 Action 的前提:
类型参数就是约束,写错了编译不过:

- Model 实现 `models.ActiveRecord`(`Generate` / `GetId` / `TableName`)
- 列表 DTO 实现 `dto.Index`,增改删 DTO 实现 `dto.Control`
- **所有 `Generate()` 必须返回副本** —— Action 在并发请求间复用实例,
就地返回会串数据(`app/demo` 的测试锁定了这一点)
- Model 需有 `TableName` / `GetId`,并内嵌 `models.ControlBy`(提供 `SetCreateBy` / `SetUpdateBy`)
- 列表 DTO:`Bind`、`GetNeedSearch`,内嵌 `dto.Pagination`
- 增改 DTO:`Bind` 与 `ToModel() (*Model, error)`——配错模型编译不过
- 详情/删除 DTO 内嵌 `dto.ObjectById` 即可继承 `Bind` 与 `GetId`,无需重写
- 详情要返回与模型不同的结构时用 `ViewAs[Model, ById, Response]()`(见 `app/jobs`)
- **不需要 `Generate()`**:每个请求都新建自己的值,不存在跨请求共享的实例

旧的 `IndexAction` 等五个仍可用,已标记 Deprecated。它们在并发请求间复用
注册时传入的实例,所以依赖「所有 `Generate()` 必须返回副本」这条约定——
仍在用旧写法的模块要继续遵守它。

仅当业务超出单表 CRUD(跨表事务、外部调用、复杂校验)时才自行编写 Api
与 Service,写法见下。
Expand Down
7 changes: 0 additions & 7 deletions app/demo/models/demo_product.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,6 @@ func (DemoProduct) TableName() string {
return "demo_product"
}

// Generate 返回副本,供通用 Action 使用。
// 必须返回新实例:Action 在并发请求间复用同一个模型指针,就地返回会串数据。
func (e *DemoProduct) Generate() models.ActiveRecord {
o := *e
return &o
}

func (e *DemoProduct) GetId() interface{} {
return e.Id
}
19 changes: 5 additions & 14 deletions app/demo/router/demo_product.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,21 +29,12 @@ func registerDemoProductRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMi
Use(authMiddleware.MiddlewareFunc()). // JWT 认证
Use(middleware.AuthCheckRole()) // Casbin 鉴权
{
m := &models.DemoProduct{}

// actions.PermissionAction() 注入数据权限上下文,
// 列表与详情缺少它会绕过 DataScope 过滤
r.GET("", actions.PermissionAction(), actions.IndexAction(m, new(dto.DemoProductSearch), func() interface{} {
list := make([]models.DemoProduct, 0)
return &list
}))

r.GET("/:id", actions.PermissionAction(), actions.ViewAction(new(dto.DemoProductById), func() interface{} {
return &models.DemoProduct{}
}))

r.POST("", actions.CreateAction(new(dto.DemoProductControl)))
r.PUT("/:id", actions.PermissionAction(), actions.UpdateAction(new(dto.DemoProductControl)))
r.DELETE("", actions.PermissionAction(), actions.DeleteAction(new(dto.DemoProductById)))
r.GET("", actions.PermissionAction(), actions.Index[models.DemoProduct, dto.DemoProductSearch]())
r.GET("/:id", actions.PermissionAction(), actions.View[models.DemoProduct, dto.DemoProductById]())
r.POST("", actions.Create[models.DemoProduct, dto.DemoProductControl]())
r.PUT("/:id", actions.PermissionAction(), actions.Update[models.DemoProduct, dto.DemoProductControl]())
r.DELETE("", actions.PermissionAction(), actions.Delete[models.DemoProduct, dto.DemoProductById]())
}
}
33 changes: 6 additions & 27 deletions app/demo/service/dto/demo_product.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,10 @@ func (m *DemoProductSearch) Bind(ctx *gin.Context) error {
return ctx.ShouldBind(m)
}

func (m *DemoProductSearch) Generate() dto.Index {
o := *m
return &o
}

// DemoProductControl 新增与修改共用的入参
// DemoProductControl is the request body of both create and update.
//
// 通用 Action(Create / Update)通过 GenerateM 拿到落库对象,
// 因此这里不直接暴露 Model,字段校验用 validate tag 声明。
// actions.Create / actions.Update get the row to write from ToModel, so the
// model itself is not exposed; field rules are declared with validate tags.
type DemoProductControl struct {
Id int `json:"id" comment:"主键"`
Name string `json:"name" comment:"名称" validate:"required"`
Expand All @@ -58,16 +53,9 @@ func (s *DemoProductControl) Bind(ctx *gin.Context) error {
return ctx.ShouldBind(s)
}

func (s *DemoProductControl) Generate() dto.Control {
o := *s
return &o
}

func (s *DemoProductControl) GetId() interface{} { return s.Id }

// GenerateM 组装落库对象。CreateBy / UpdateBy 由通用 Action 在此之后注入,
// 此处不要手动赋值。
func (s *DemoProductControl) GenerateM() (common.ActiveRecord, error) {
// ToModel builds the row to write. The actions set CreateBy / UpdateBy
// afterwards, so do not set them here.
func (s *DemoProductControl) ToModel() (*models.DemoProduct, error) {
return &models.DemoProduct{
Model: common.Model{Id: s.Id},
Name: s.Name,
Expand All @@ -85,12 +73,3 @@ type DemoProductById struct {

// Bind 与 GetId 由内嵌的 dto.ObjectById 提供:它已处理好 uri 绑定、
// DELETE 时的批量 ids 合并与参数校验,无需在此重复实现。

func (s *DemoProductById) Generate() dto.Control {
o := *s
return &o
}

func (s *DemoProductById) GenerateM() (common.ActiveRecord, error) {
return &models.DemoProduct{}, nil
}
76 changes: 7 additions & 69 deletions app/demo/service/dto/demo_product_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,83 +4,21 @@ import (
"testing"

"go-admin/app/demo/models"
"go-admin/common/dto"
common "go-admin/common/models"
)

// 通用 Action 依赖 DTO 与 Model 实现一组接口。这些约束在编译期无法完全覆盖
// (接口是在路由注册处才被要求的),因此用测试锁定,避免改动后在运行时才暴露。

func TestImplementsIndexInterface(t *testing.T) {
var _ dto.Index = (*DemoProductSearch)(nil)
}

func TestImplementsControlInterface(t *testing.T) {
var _ dto.Control = (*DemoProductControl)(nil)
var _ dto.Control = (*DemoProductById)(nil)
}

func TestModelImplementsActiveRecord(t *testing.T) {
var _ common.ActiveRecord = (*models.DemoProduct)(nil)
}

// Generate 必须返回副本:通用 Action 在并发请求间复用同一个实例,
// 就地返回会导致请求之间串数据。
func TestGenerateReturnsCopy(t *testing.T) {
src := &DemoProductControl{Id: 1, Name: "原始"}
got := src.Generate().(*DemoProductControl)

if got == src {
t.Fatal("Generate 返回了同一指针,应返回副本")
}
got.Name = "被修改"
if src.Name != "原始" {
t.Errorf("修改副本影响了原对象:src.Name = %q", src.Name)
}
}

func TestSearchGenerateReturnsCopy(t *testing.T) {
src := &DemoProductSearch{Name: "原始"}
got := src.Generate().(*DemoProductSearch)

if got == src {
t.Fatal("Generate 返回了同一指针,应返回副本")
}
got.Name = "被修改"
if src.Name != "原始" {
t.Errorf("修改副本影响了原对象:src.Name = %q", src.Name)
}
}

func TestModelGenerateReturnsCopy(t *testing.T) {
src := &models.DemoProduct{Name: "原始"}
got := src.Generate().(*models.DemoProduct)

if got == src {
t.Fatal("Generate 返回了同一指针,应返回副本")
}
got.Name = "被修改"
if src.Name != "原始" {
t.Errorf("修改副本影响了原对象:src.Name = %q", src.Name)
}
}

// GenerateM 组装落库对象,主键需正确传递,否则更新会退化成插入。
func TestGenerateMCarriesId(t *testing.T) {
// ToModel builds the row to write; the key has to reach it, or an update
// matches no row.
func TestToModelCarriesId(t *testing.T) {
c := &DemoProductControl{Id: 42, Name: "示例", Code: "P-42", Price: 9.9}
m, err := c.GenerateM()
p, err := c.ToModel()
if err != nil {
t.Fatalf("GenerateM 返回错误: %v", err)
}
p, ok := m.(*models.DemoProduct)
if !ok {
t.Fatalf("GenerateM 返回类型错误: %T", m)
t.Fatalf("ToModel: %v", err)
}
if p.Id != 42 {
t.Errorf("主键未传递: got %d, want 42", p.Id)
t.Errorf("key not carried: got %d, want 42", p.Id)
}
if p.Name != "示例" || p.Code != "P-42" || p.Price != 9.9 {
t.Errorf("字段映射有误: %+v", p)
t.Errorf("fields mapped wrongly: %+v", p)
}
}

Expand Down
5 changes: 0 additions & 5 deletions app/jobs/models/sys_job.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,6 @@ func (*SysJob) TableName() string {
return "sys_job"
}

func (e *SysJob) Generate() models.ActiveRecord {
o := *e
return &o
}

func (e *SysJob) GetId() interface{} {
return e.JobId
}
Expand Down
18 changes: 7 additions & 11 deletions app/jobs/router/sys_job.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,13 @@ func registerSysJobRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddlew

r := v1.Group("/sysjob").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
sysJob := &models2.SysJob{}
r.GET("", actions.PermissionAction(), actions.IndexAction(sysJob, new(dto2.SysJobSearch), func() interface{} {
list := make([]models2.SysJob, 0)
return &list
}))
r.GET("/:id", actions.PermissionAction(), actions.ViewAction(new(dto2.SysJobById), func() interface{} {
return &dto2.SysJobItem{}
}))
r.POST("", actions.CreateAction(new(dto2.SysJobControl)))
r.PUT("", actions.PermissionAction(), actions.UpdateAction(new(dto2.SysJobControl)))
r.DELETE("", actions.PermissionAction(), actions.DeleteAction(new(dto2.SysJobById)))
r.GET("", actions.PermissionAction(), actions.Index[models2.SysJob, dto2.SysJobSearch]())
// The detail answers SysJobItem, whose entryId the edit form reads;
// the model itself marshals it as entry_id.
r.GET("/:id", actions.PermissionAction(), actions.ViewAs[models2.SysJob, dto2.SysJobById, dto2.SysJobItem]())
r.POST("", actions.Create[models2.SysJob, dto2.SysJobControl]())
r.PUT("", actions.PermissionAction(), actions.Update[models2.SysJob, dto2.SysJobControl]())
r.DELETE("", actions.PermissionAction(), actions.Delete[models2.SysJob, dto2.SysJobById]())
}
sysJob := apis.SysJob{}

Expand Down
26 changes: 1 addition & 25 deletions app/jobs/service/dto/sys_job.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"go-admin/app/jobs/models"

"go-admin/common/dto"
common "go-admin/common/models"
)

type SysJobSearch struct {
Expand All @@ -32,11 +31,6 @@ func (m *SysJobSearch) Bind(ctx *gin.Context) error {
return err
}

func (m *SysJobSearch) Generate() dto.Index {
o := *m
return &o
}

type SysJobControl struct {
JobId int `json:"jobId"`
JobName string `json:"jobName" validate:"required"` // 名称
Expand All @@ -55,12 +49,7 @@ func (s *SysJobControl) Bind(ctx *gin.Context) error {
return ctx.ShouldBind(s)
}

func (s *SysJobControl) Generate() dto.Control {
cp := *s
return &cp
}

func (s *SysJobControl) GenerateM() (common.ActiveRecord, error) {
func (s *SysJobControl) ToModel() (*models.SysJob, error) {
return &models.SysJob{
JobId: s.JobId,
JobName: s.JobName,
Expand All @@ -76,23 +65,10 @@ func (s *SysJobControl) GenerateM() (common.ActiveRecord, error) {
}, nil
}

func (s *SysJobControl) GetId() interface{} {
return s.JobId
}

type SysJobById struct {
dto.ObjectById
}

func (s *SysJobById) Generate() dto.Control {
cp := *s
return &cp
}

func (s *SysJobById) GenerateM() (common.ActiveRecord, error) {
return &models.SysJob{}, nil
}

type SysJobItem struct {
JobId int `json:"jobId"`
JobName string `json:"jobName" validate:"required"` // 名称
Expand Down
6 changes: 5 additions & 1 deletion common/actions/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ import (
)

// CreateAction 通用新增动作
//
// Deprecated: Use Create[Model, Control](). It builds its values per request, so the
// Generate() copies this action depends on are not needed, and a model
// paired with the wrong request does not compile. See generic.go.
func CreateAction(control dto.Control) gin.HandlerFunc {
return func(c *gin.Context) {
log := api.GetRequestLogger(c)
Expand All @@ -37,7 +41,7 @@ func CreateAction(control dto.Control) gin.HandlerFunc {
return
}
object.SetCreateBy(user.GetUserId(c))
err = db.WithContext(c).Create(object).Error
err = db.WithContext(c.Request.Context()).Create(object).Error
if err != nil {
log.Errorf("Create error: %s", err)
response.Error(c, 500, err, "创建失败")
Expand Down
Loading
Loading