Skip to content

Commit

Permalink
1.sail关键字新增marshal日志支持,2.orm代码优化、新增hook时间支持,3.响应器新增语言码,4.utils新增numbe…
Browse files Browse the repository at this point in the history
…r相关方法
  • Loading branch information
keepchen committed Jun 10, 2024
1 parent 869966f commit b52fc1a
Show file tree
Hide file tree
Showing 11 changed files with 367 additions and 30 deletions.
3 changes: 3 additions & 0 deletions constants/code.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ func RegisterCodeTable(language LanguageCode, i18nMsg map[ICodeType]string) {
// # 此方法适用于【动态】注入单个错误码的场景
func RegisterCodeSingle(language LanguageCode, code ICodeType, msg string) {
ctm.mux.Lock()
if _, ok := ctm.maps[language][code]; !ok {
ctm.maps[language] = make(map[ICodeType]string)
}
ctm.maps[language][code] = msg
ctm.mux.Unlock()
}
Expand Down
8 changes: 6 additions & 2 deletions constants/i18n.go
Original file line number Diff line number Diff line change
Expand Up @@ -272,12 +272,16 @@ var i18n = []LanguageCode{
LanguageZulu,
}

func (lc LanguageCode) String() string {
return string(lc)
}

func (lc LanguageCode) ToLowerCase() string {
return strings.ToLower(string(lc))
return strings.ToLower(lc.String())
}

func (lc LanguageCode) ToUpperCase() string {
return strings.ToUpper(string(lc))
return strings.ToUpper(lc.String())
}

func (lc LanguageCode) Exist() bool {
Expand Down
6 changes: 6 additions & 0 deletions http/api/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ var (
forceHttpCode200 = false //强制使用200作为http的状态码
timezone = constants.DefaultTimeZone //时区
detectAcceptLanguage = false //是否检测客户端语言
languageCode = constants.LanguageEnglish //语言代码
)

var (
Expand All @@ -35,6 +36,10 @@ type Option struct {
Timezone string
//是否检测客户端语言,用于错误码消息返回
DetectAcceptLanguage bool
//语言代码
//
//当没有启用 DetectAcceptLanguage 时,使用该语言代码
LanguageCode constants.LanguageCode
}

const (
Expand Down Expand Up @@ -91,5 +96,6 @@ func DefaultSetupOption() *Option {
ErrNoneCode: constants.ErrNone,
ErrNoneCodeMsg: "SUCCESS",
ForceHttpCode200: true,
LanguageCode: constants.LanguageEnglish,
}
}
2 changes: 1 addition & 1 deletion http/api/response.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ func (a *responseEngine) mergeBody(code constants.ICodeType, resp interface{}, m
body dto.Base
requestId string
httpCode int
language = []string{"en"}
language = []string{languageCode.String()}
)
//从上下文中获取语言代码
if detectAcceptLanguage {
Expand Down
7 changes: 7 additions & 0 deletions orm/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,10 @@ type BaseModel struct {

// NoneID 空ID
const NoneID = uint64(0)

var nowTime = time.Now()

// SetHookTime 设置勾子函数的时间对象
func SetHookTime(now time.Time) {
nowTime = now
}
10 changes: 4 additions & 6 deletions orm/hook.go
Original file line number Diff line number Diff line change
@@ -1,33 +1,31 @@
package orm

import (
"time"

"gorm.io/gorm"
)

func (u *BaseModel) BeforeSave(_ *gorm.DB) (err error) {
u.CreatedAt = time.Now()
u.CreatedAt = nowTime
u.UpdatedAt = u.CreatedAt

return nil
}

func (u *BaseModel) BeforeCreate(_ *gorm.DB) (err error) {
u.CreatedAt = time.Now()
u.CreatedAt = nowTime
u.UpdatedAt = u.CreatedAt

return nil
}

func (u *BaseModel) BeforeUpdate(_ *gorm.DB) (err error) {
u.UpdatedAt = time.Now()
u.UpdatedAt = nowTime

return nil
}

func (u *BaseModel) BeforeDelete(_ *gorm.DB) (err error) {
now := time.Now()
now := nowTime
u.DeletedAt = &now

return nil
Expand Down
55 changes: 44 additions & 11 deletions orm/svc.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,23 +36,23 @@ type Svc interface {
Session(session *gorm.Session) Svc
WithContext(ctx context.Context) Svc

Count(count *int64)
Create(value interface{}) error
Find(dest interface{}, conditions ...interface{}) error

First(dest interface{}, conditions ...interface{}) error
Updates(values interface{}) error
Save(values interface{}) error
Delete(value interface{}, conditions ...interface{}) error
Transaction(fc func(tx *gorm.DB) error, opts ...*sql.TxOptions) (err error)

//Unwrap 返回gorm原生实例
// Unwrap 返回gorm原生实例
Unwrap() *gorm.DB

//R 使用读实例
// R 使用读实例
R() Svc
//W 使用写实例
// W 使用写实例
W() Svc
//Paginate 分页查询(多行)
// Paginate 分页查询(多行)
//
//参数:
//
Expand All @@ -64,11 +64,11 @@ type Svc interface {
//
//总条数和错误
Paginate(dest interface{}, page, pageSize int) (int64, error)
//FindOrNil 查询多条记录
// FindOrNil 查询多条记录
//
//如果记录不存在忽略 gorm.ErrRecordNotFound 错误
FindOrNil(dest interface{}, conditions ...interface{}) error
//FirstOrNil 查询单条记录
// FirstOrNil 查询单条记录
//
//如果记录不存在忽略 gorm.ErrRecordNotFound 错误
FirstOrNil(dest interface{}, conditions ...interface{}) error
Expand Down Expand Up @@ -255,8 +255,22 @@ func (a *SvcImpl) Unwrap() *gorm.DB {
return a.tx
}

func (a *SvcImpl) Count(count *int64) {
if a.tx == nil {
a.tx = a.dbw
}

a.tx.Count(count)
a.clearTx()
}

func (a *SvcImpl) Create(value interface{}) error {
err := a.dbw.Create(value).Error
if a.tx == nil {
a.tx = a.dbw
}

err := a.tx.Create(value).Error
a.clearTx()

if err != nil {
a.logger.Error("[Database service]:Create:Error",
Expand All @@ -273,6 +287,7 @@ func (a *SvcImpl) Find(dest interface{}, conditions ...interface{}) error {
}

err := IgnoreErrRecordNotFound(a.tx.Find(dest, conditions...))
a.clearTx()

if err != nil {
a.logger.Error("[Database service]:Find:Error",
Expand All @@ -290,6 +305,7 @@ func (a *SvcImpl) FindOrNil(dest interface{}, conditions ...interface{}) error {
}

err := IgnoreErrRecordNotFound(a.tx.Find(dest, conditions...))
a.clearTx()

if err != nil {
a.logger.Error("[Database service]:FindOrNil:Error",
Expand All @@ -307,6 +323,7 @@ func (a *SvcImpl) First(dest interface{}, conditions ...interface{}) error {
}

err := IgnoreErrRecordNotFound(a.tx.First(dest, conditions...))
a.clearTx()

if err != nil {
a.logger.Error("[Database service]:First:Error",
Expand All @@ -324,6 +341,7 @@ func (a *SvcImpl) FirstOrNil(dest interface{}, conditions ...interface{}) error
}

err := IgnoreErrRecordNotFound(a.tx.First(dest, conditions...))
a.clearTx()

if err != nil {
a.logger.Error("[Database service]:FirstOrNil:Error",
Expand All @@ -341,6 +359,7 @@ func (a *SvcImpl) Updates(values interface{}) error {
}

err := a.tx.Updates(values).Error
a.clearTx()

if err != nil {
a.logger.Error("[Database service]:Updates:Error",
Expand All @@ -357,6 +376,7 @@ func (a *SvcImpl) Save(values interface{}) error {
}

err := a.tx.Save(values).Error
a.clearTx()

if err != nil {
a.logger.Error("[Database service]:Save:Error",
Expand All @@ -371,7 +391,9 @@ func (a *SvcImpl) Delete(value interface{}, conditions ...interface{}) error {
if a.tx == nil {
a.tx = a.dbw
}

err := a.tx.Delete(value, conditions...).Error
a.clearTx()

if err != nil {
a.logger.Error("[Database service]:Delete:Error",
Expand All @@ -387,7 +409,9 @@ func (a *SvcImpl) Transaction(fc func(tx *gorm.DB) error, opts ...*sql.TxOptions
if a.tx == nil {
a.tx = a.dbw
}

err = a.tx.Transaction(fc, opts...)
a.clearTx()

if err != nil {
a.logger.Error("[Database service]:Transaction:Error",
Expand Down Expand Up @@ -418,16 +442,25 @@ func (a *SvcImpl) Paginate(dest interface{}, page, pageSize int) (int64, error)
a.tx = a.dbw
}

var total int64
a.tx.Count(&total)
var count int64
if a.tx.Statement.Model == nil {
a.tx.Model(dest).Count(&count)
} else {
a.tx.Count(&count)
}

err := IgnoreErrRecordNotFound(a.tx.Scopes(Paginate(page, pageSize)).Find(dest))
a.clearTx()

if err != nil {
a.logger.Error("[Database service]:Paginate:Error",
zap.String("value", logger.MarshalInterfaceValue(dest)),
zap.Errors("errors", []error{err}))
}

return total, err
return count, err
}

func (a *SvcImpl) clearTx() {
a.tx = nil
}
Loading

0 comments on commit b52fc1a

Please sign in to comment.