Skip to content

Commit

Permalink
refactor(cmfx/user/settings): 统一类型名称格式
Browse files Browse the repository at this point in the history
  • Loading branch information
caixw committed Dec 4, 2024
1 parent 5ebc051 commit 9836d67
Show file tree
Hide file tree
Showing 9 changed files with 32 additions and 25 deletions.
1 change: 1 addition & 0 deletions cmfx/initial/cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ func initServer(id, ver string, o *server.Options, user *Config, action string)
doc := openapi.New(s, web.Phrase("The api doc of %s", s.ID()),
openapi.WithMediaType(json.Mimetype, cbor.Mimetype),
openapi.WithProblemResponse(),
openapi.WithTag("admin", web.Phrase("admin tag"), "", nil),
openapi.WithContact("caixw", "", "https://github.com/caixw"),
openapi.WithSecurityScheme(token.SecurityScheme("token", web.Phrase("token auth"))),
swagger.WithCDN(""),
Expand Down
13 changes: 9 additions & 4 deletions cmfx/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ const (
type serverVarsKey int

// Module 表示代码模块的基本信息
//
// Module 是代码复用的基本单元,根据模块 ID 不同,会生成不同的表名称,从尔达到整个单元复用的目的。
type Module struct {
id string
desc web.LocaleStringer
Expand All @@ -35,7 +37,8 @@ type Module struct {
doc *openapi.Document
}

func newModule(id string, desc web.LocaleStringer, s web.Server, db *orm.DB, r *web.Router, doc *openapi.Document) *Module {
// NewModule 声明新模块
func NewModule(id string, desc web.LocaleStringer, s web.Server, db *orm.DB, r *web.Router, doc *openapi.Document) *Module {
// 防止重复的 id 值
m, loaded := s.Vars().LoadOrStore(moduleKey, map[string]struct{}{id: {}})
if loaded {
Expand Down Expand Up @@ -79,12 +82,14 @@ func (m *Module) Engine(tx *orm.Tx) orm.Engine {

// New 基于当前模块的 ID 声明一个新的实例
func (m *Module) New(id string, desc web.LocaleStringer) *Module {
return newModule(m.ID()+id, desc, m.Server(), m.DB(), m.Router(), m.doc)
return NewModule(m.ID()+id, desc, m.Server(), m.DB(), m.Router(), m.doc)
}

// 当前模块关联的路由对象
func (m *Module) Router() *web.Router { return m.r }

func (m *Module) OpenAPI() *openapi.Document { return m.doc }

// 创建 openapi 文档的中间件
func (m *Module) API(f func(o *openapi.Operation)) web.Middleware {
return m.doc.API(f)
Expand All @@ -102,10 +107,10 @@ func Init(s web.Server, limit *ratelimit.Ratelimit, db *orm.DB, router *web.Rout

s.OnClose(func() error { return db.Close() })

return newModule("", web.Phrase("root module"), s, db, router, doc)
return NewModule("", web.Phrase("root module"), s, db, router, doc)
}

// Unlimit 取消由 [InitFromConfig] 或 [Init] 创建的 API 访问次数限制功能
// Unlimit 取消由 [Init] 创建的 API 访问次数限制功能
func Unlimit(s web.Server) web.Middleware {
if v, ok := s.Vars().Load(limitKey); ok {
return (v.(*ratelimit.Ratelimit)).Unlimit()
Expand Down
4 changes: 2 additions & 2 deletions cmfx/module_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func TestNewModule(t *testing.T) {
r := srv.Routers().New("def", nil)
doc := openapi.New(srv, web.Phrase("test"))

mod := newModule("m1", web.Phrase("m1"), srv, db, r, doc)
mod := NewModule("m1", web.Phrase("m1"), srv, db, r, doc)
a.NotNil(mod).
Equal(mod.ID(), "m1").
Equal(mod.Server(), srv).
Expand All @@ -67,7 +67,7 @@ func TestNewModule(t *testing.T) {

a.PanicString(func() {
doc := openapi.New(srv, web.Phrase("test"))
newModule("m1sub", web.Phrase("m1sub"), srv, db, r, doc)
NewModule("m1sub", web.Phrase("m1sub"), srv, db, r, doc)
}, "存在相同 id 的模块:m1sub")

a.Equal(mod2.Engine(nil), mod2.DB())
Expand Down
2 changes: 1 addition & 1 deletion cmfx/user/settings/install.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (

func Install(mod *cmfx.Module, tableName string) {
db := buildDB(mod, tableName)
if err := db.Create(&modelSetting{}); err != nil {
if err := db.Create(&settingPO{}); err != nil {
panic(web.SprintError(mod.Server().Locale().Printer(), true, err))
}
}
Expand Down
4 changes: 2 additions & 2 deletions cmfx/user/settings/install_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,12 @@ func TestInstallObject(t *testing.T) {

// 检测字段是都写入

f1 := &modelSetting{Group: "opt", Key: "f1", UID: sql.NullInt64{Valid: true, Int64: 0}}
f1 := &settingPO{Group: "opt", Key: "f1", UID: sql.NullInt64{Valid: true, Int64: 0}}
found, err := ss.db.Select(f1)
a.NotError(err).True(found)

// 零值也正常写入
f2 := &modelSetting{Group: "opt", Key: "F2", UID: sql.NullInt64{Valid: true, Int64: 0}}
f2 := &settingPO{Group: "opt", Key: "F2", UID: sql.NullInt64{Valid: true, Int64: 0}}
found, err = ss.db.Select(f2)
a.NotError(err).True(found)
}
6 changes: 3 additions & 3 deletions cmfx/user/settings/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"time"
)

type modelSetting struct {
type settingPO struct {
ID int64 `orm:"name(id);ai"`
Group string `orm:"name(group);len(20);unique(group_key_uid)"`
Key string `orm:"name(key);len(20);unique(group_key_uid)"`
Expand All @@ -18,11 +18,11 @@ type modelSetting struct {
Created time.Time `orm:"name(time)"`
}

func (l *modelSetting) BeforeInsert() error {
func (l *settingPO) BeforeInsert() error {
if l.Created.IsZero() {
l.Created = time.Now()
}
return nil
}

func (l *modelSetting) TableName() string { return `` }
func (l *settingPO) TableName() string { return `` }
2 changes: 1 addition & 1 deletion cmfx/user/settings/models_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ package settings

import "github.com/issue9/orm/v6"

var _ orm.TableNamer = &modelSetting{}
var _ orm.TableNamer = &settingPO{}
21 changes: 11 additions & 10 deletions cmfx/user/settings/object.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ import (
"reflect"
"slices"

"github.com/issue9/cmfx/cmfx"
"github.com/issue9/orm/v6"
"github.com/issue9/web"

"github.com/issue9/cmfx/cmfx"
)

const tag = "setting"
Expand All @@ -42,8 +43,8 @@ type Sanitizer interface {
type Object[T any] struct {
id string
s *Settings
preset []*modelSetting // 保存着从数据库中加载的默认用户的设置对象
users map[int64]*T // 缓存的对象
preset []*settingPO // 保存着从数据库中加载的默认用户的设置对象
users map[int64]*T // 缓存的对象
}

func checkObjectType[T any]() {
Expand All @@ -61,7 +62,7 @@ func LoadObject[T any](s *Settings, id string) (*Object[T], error) {
}
checkObjectType[T]()

ss := make([]*modelSetting, 0, 10)
ss := make([]*settingPO, 0, 10)
size, err := s.db.Where("uid=?", s.presetUID).And("{group}=?", id).Select(true, &ss)
if err != nil {
return nil, err
Expand Down Expand Up @@ -94,7 +95,7 @@ func (obj *Object[T]) Get(uid int64) (*T, error) {
// 尝试从数据库加载数据

var o T
ss := make([]*modelSetting, 0, 10)
ss := make([]*settingPO, 0, 10)
size, err := obj.s.db.Where("uid=?", uid).And("{group}=?", obj.id).Select(true, &ss)
if err != nil {
return &o, err
Expand Down Expand Up @@ -163,10 +164,10 @@ func (obj *Object[T]) HandlePut(ctx *web.Context, uid int64) web.Responser {
}

// 将 o 转换为 []*modelSetting
func toModels[T any](o *T, uid int64, g string) ([]*modelSetting, error) {
func toModels[T any](o *T, uid int64, g string) ([]*settingPO, error) {
rv := reflect.ValueOf(o).Elem()
size := rv.NumField()
ss := make([]*modelSetting, 0, size)
ss := make([]*settingPO, 0, size)

rt := rv.Type()
for i := range size {
Expand All @@ -179,7 +180,7 @@ func toModels[T any](o *T, uid int64, g string) ([]*modelSetting, error) {
if err != nil {
return nil, err
}
ss = append(ss, &modelSetting{UID: sql.NullInt64{Int64: uid, Valid: true}, Group: g, Key: key, Value: string(data)})
ss = append(ss, &settingPO{UID: sql.NullInt64{Int64: uid, Valid: true}, Group: g, Key: key, Value: string(data)})
}

if err := callSanitizer(o); err != nil {
Expand All @@ -189,7 +190,7 @@ func toModels[T any](o *T, uid int64, g string) ([]*modelSetting, error) {
}

// 从 []modelSetting 转换为 o
func fromModels[T any](ss []*modelSetting, o *T, g string) error {
func fromModels[T any](ss []*settingPO, o *T, g string) error {
rv := reflect.ValueOf(o).Elem()
rt := rv.Type()

Expand All @@ -199,7 +200,7 @@ func fromModels[T any](ss []*modelSetting, o *T, g string) error {
continue
}

index := slices.IndexFunc(ss, func(s *modelSetting) bool { return s.Key == key && s.Group == g })
index := slices.IndexFunc(ss, func(s *settingPO) bool { return s.Key == key && s.Group == g })
if index < 0 {
panic(fmt.Sprintf("不存在的字段:%s,%s", g, key))
}
Expand Down
4 changes: 2 additions & 2 deletions cmfx/user/settings/object_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func TestObject(t *testing.T) {
Equal(opt.F2, 2).
Equal(opt.F1, "f1").
Length(obj.users, 1)
size, err := ss.db.Where("uid=?", 1).Select(true, &modelSetting{})
size, err := ss.db.Where("uid=?", 1).Select(true, &settingPO{})
a.NotError(err).Zero(size) // 未存入数据库

// Object.Set
Expand All @@ -66,7 +66,7 @@ func TestObject(t *testing.T) {
a.NotError(err).NotNil(opt).
Equal(opt.F2, 1).
Length(obj.users, 1) // 主动写入了数据
size, err = ss.db.Where("uid=?", 1).Select(true, &modelSetting{})
size, err = ss.db.Where("uid=?", 1).Select(true, &settingPO{})
a.NotError(err).Equal(size, 1) // 已入数据库
}

Expand Down

0 comments on commit 9836d67

Please sign in to comment.