service_context.go 2.6 KB
package svc

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

type ServiceContext struct {
	Config                                         config.Config
	DB                                             *gorm.DB
	Redis                                          *redis.Redis
	LogRequest                                     rest.Middleware
	LoginStatusCheck                               rest.Middleware
	ApiAuthService                                 authlib.ApiAuthService
	SmsService                                     smslib.SMSService
	OpenApiService                                 openlib.OpenApiService
	BsiActivityRepository                          domain.BsiActivityRepository
	BsiActivityQuestionnaireSubmitRecordRepository domain.BsiActivityQuestionnaireSubmitRecordRepository
}

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"})
	apiAuth := authlib.ApiAuthService{
		Service: gateway.NewService(c.ApiAuth.Name, c.ApiAuth.Host, c.ApiAuth.Timeout),
	}

	return &ServiceContext{
		Config:                c,
		DB:                    db,
		Redis:                 redis,
		ApiAuthService:        apiAuth,
		LogRequest:            middleware.NewLogRequestMiddleware(c.LogRequest).Handle,
		LoginStatusCheck:      middleware.NewLoginStatusCheckMiddleware(apiAuth).Handle,
		BsiActivityRepository: repository.NewBsiActivityRepository(cache.NewCachedRepository(mlCache)),
		BsiActivityQuestionnaireSubmitRecordRepository: repository.NewBsiActivityQuestionnaireSubmitRecordRepository(cache.NewCachedRepository(mlCache)),
	}
}

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