98 lines
2.4 KiB
Go
98 lines
2.4 KiB
Go
package svc
|
|
|
|
import (
|
|
"fmt"
|
|
"reflect"
|
|
"strings"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
|
|
mon "mongo.games.com/game/mongo"
|
|
"mongo.games.com/game/util/viperx"
|
|
"mongo.games.com/goserver/core/logger"
|
|
)
|
|
|
|
// ServiceContext 服务上下文
|
|
// 依赖注入
|
|
type ServiceContext struct {
|
|
}
|
|
|
|
func NewServiceContext() *ServiceContext {
|
|
|
|
vp := viperx.GetViper("mgo", "json")
|
|
// mongo初始化
|
|
conf := &mon.Config{}
|
|
err := vp.Unmarshal(conf)
|
|
if err != nil {
|
|
panic(fmt.Errorf("mongo config error: %v", err))
|
|
}
|
|
mon.Init(conf)
|
|
|
|
return &ServiceContext{}
|
|
}
|
|
|
|
type TableName interface {
|
|
TableName() string
|
|
}
|
|
|
|
// GetTableName 获取表名
|
|
func GetTableName(model any) string {
|
|
if m, ok := model.(TableName); ok {
|
|
return m.TableName()
|
|
}
|
|
|
|
t := reflect.TypeOf(model)
|
|
if t.Kind() == reflect.Ptr {
|
|
t = t.Elem()
|
|
}
|
|
if t.Kind() != reflect.Struct {
|
|
panic("model must be a struct or a pointer to a struct")
|
|
}
|
|
|
|
return strings.ToLower(t.Name())
|
|
}
|
|
|
|
// GetUserCollection 用户库
|
|
func GetUserCollection[T any](platform string, model any, f func(database *mongo.Database, c *mongo.Collection) T) (T, error) {
|
|
c, err := mon.GetUserCollection(platform, GetTableName(model))
|
|
if err != nil {
|
|
var z T
|
|
logger.Logger.Errorf("GetUserCollection error: %v", err)
|
|
return z, err
|
|
}
|
|
return f(c.Database.Database, c.Collection), nil
|
|
}
|
|
|
|
// GetLogCollection 日志库
|
|
func GetLogCollection[T any](platform string, model any, f func(database *mongo.Database, c *mongo.Collection) T) (T, error) {
|
|
c, err := mon.GetLogCollection(platform, GetTableName(model))
|
|
if err != nil {
|
|
var z T
|
|
logger.Logger.Errorf("GetLogCollection error: %v", err)
|
|
return z, err
|
|
}
|
|
return f(c.Database.Database, c.Collection), nil
|
|
}
|
|
|
|
// GetGlobalUserCollection 全局用户库
|
|
func GetGlobalUserCollection[T any](model any, f func(database *mongo.Database, c *mongo.Collection) T) (T, error) {
|
|
c, err := mon.GetGlobalUserCollection(GetTableName(model))
|
|
if err != nil {
|
|
var z T
|
|
logger.Logger.Errorf("GetGlobalUserCollection error: %v", err)
|
|
return z, err
|
|
}
|
|
return f(c.Database.Database, c.Collection), nil
|
|
}
|
|
|
|
// GetGlobalLogCollection 全局日志库
|
|
func GetGlobalLogCollection[T any](model any, f func(database *mongo.Database, c *mongo.Collection) T) (T, error) {
|
|
c, err := mon.GetGlobalLogCollection(GetTableName(model))
|
|
if err != nil {
|
|
var z T
|
|
logger.Logger.Errorf("GetGlobalLogCollection error: %v", err)
|
|
return z, err
|
|
}
|
|
return f(c.Database.Database, c.Collection), nil
|
|
}
|