service_context.go 1.9 KB
package svc

import (
	"github.com/tiptok/gocomm/pkg/cache/gzcache"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/api/internal/config"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/interanl/pkg/db/repository"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/interanl/pkg/db/transaction"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/interanl/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/interanl/pkg/gateway"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/interanl/pkg/gateway/bytelib"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/pkg/cache"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/pkg/database"
	"gorm.io/gorm"
)

type ServiceContext struct {
	Config          config.Config
	DB              *gorm.DB
	Redis           *redis.Redis
	RedisCache      gzcache.GZCache
	ChartRepository domain.ChartRepository

	ByteMetadataService bytelib.ByteMetadataService
}

func NewServiceContext(c config.Config) *ServiceContext {
	db := database.OpenGormPGDB(c.DB.DataSource)
	mlCache := cache.NewMultiLevelCache([]string{c.Redis.Host}, c.Redis.Pass)
	redisCache := gzcache.NewClusterCache([]string{c.Redis.Host}, c.Redis.Pass)
	redis, _ := redis.NewRedis(redis.RedisConf{Host: c.Redis.Host, Pass: c.Redis.Pass, Type: "node"})

	return &ServiceContext{
		Config:          c,
		DB:              db,
		RedisCache:      redisCache,
		Redis:           redis,
		ChartRepository: repository.NewChartRepository(cache.NewCachedRepository(mlCache)),

		ByteMetadataService: bytelib.ByteMetadataService{
			Service: gateway.NewService(c.ByteMetadata.Name, c.ByteMetadata.Host, c.ByteMetadata.Timeout),
		},
	}
}

func (svc *ServiceContext) DefaultDBConn() transaction.Conn {
	return transaction.NewTransactionContext(svc.DB)
}