service_context.go 1.3 KB
package svc

import (
	"github.com/zeromicro/go-zero/core/stores/redis"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/api/internal/config"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/interanl/pkg/db/repository"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/interanl/pkg/db/transaction"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/interanl/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/pkg/cache"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/pkg/database"
	"gorm.io/gorm"
)

type ServiceContext struct {
	Config config.Config
	DB     *gorm.DB
	Redis  *redis.Redis

	CommentRepository domain.CommentRepository
}

func NewServiceContext(c config.Config) *ServiceContext {

	db := database.OpenGormPGDB(c.DB.DataSource, c.Log.Mode)
	mlCache := cache.NewMultiLevelCache([]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,
		Redis:             redis,
		CommentRepository: repository.NewCommentRepository(cache.NewCachedRepository(mlCache)),
	}
}

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