init project
This commit is contained in:
1 parent
d63cc8d9f5
commit
ee07869839
39 files changed
+1560
-622
No files matched your search
@@ -0,0 +1,67 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"unicode/utf8"
|
||||
|
||||
"micro_layout/internal/storage/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type UserLogic struct {
|
||||
mutex sync.RWMutex
|
||||
nextID int64
|
||||
users map[int64]model.User
|
||||
}
|
||||
|
||||
func newUserLogic() *UserLogic {
|
||||
return &UserLogic{
|
||||
nextID: 2,
|
||||
users: map[int64]model.User{1: {BaseModel: model.BaseModel{ID: 1}, Name: "demo", Status: "active"}},
|
||||
}
|
||||
}
|
||||
|
||||
var ErrInvalidUser = errors.New("name must contain between 1 and 100 characters")
|
||||
|
||||
func (logic *UserLogic) Create(ctx context.Context, name string) (model.User, error) {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" || utf8.RuneCountInString(name) > 100 {
|
||||
return model.User{}, ErrInvalidUser
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
item := model.User{Name: name, Status: "active"}
|
||||
if database := Resources.Storage.DB(); database != nil {
|
||||
err := database.WithContext(ctx).Create(&item).Error
|
||||
return item, err
|
||||
}
|
||||
logic.mutex.Lock()
|
||||
defer logic.mutex.Unlock()
|
||||
item.ID = logic.nextID
|
||||
logic.nextID++
|
||||
logic.users[item.ID] = item
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (logic *UserLogic) QueryInfo(ctx context.Context, id int64) (model.User, bool, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return model.User{}, false, err
|
||||
}
|
||||
if database := Resources.Storage.DB(); database != nil {
|
||||
var item model.User
|
||||
err := database.WithContext(ctx).First(&item, id).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return model.User{}, false, nil
|
||||
}
|
||||
return item, err == nil, err
|
||||
}
|
||||
logic.mutex.RLock()
|
||||
defer logic.mutex.RUnlock()
|
||||
item, exists := logic.users[id]
|
||||
return item, exists, nil
|
||||
}
|
||||
Reference in new issue
Block a user