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/su-micro/cmd/ep/chat/api/internal/config"
	"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/chat/internal/pkg/db/repository"
	"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/chat/internal/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/open"
	"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/cache"
	"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/database"
	"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/middleware"
	"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/transaction"
	"gorm.io/gorm"
)

type ServiceContext struct {
	Config                               config.Config
	LogRequest                           rest.Middleware
	Redis                                *redis.Redis
	DB                                   *gorm.DB
	ChatSessionRepository                domain.ChatSessionRepository
	ChatSessionRecordRepository          domain.ChatSessionRecordRepository
	ChatDocumentRepository               domain.ChatDocumentRepository
	ChatDatasetRepository                domain.ChatDatasetRepository
	ChatDatasetDocumentMappingRepository domain.ChatDatasetDocumentMappingRepository
	SystemOpen                           open.SystemOpen
}

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,
		LogRequest:                           middleware.NewLogRequestMiddleware(c.LogRequest).Handle,
		ChatSessionRepository:                repository.NewChatSessionRepository(cache.NewCachedRepository(mlCache)),
		ChatSessionRecordRepository:          repository.NewChatSessionRecordRepository(cache.NewCachedRepository(mlCache)),
		ChatDocumentRepository:               repository.NewChatDocumentRepository(cache.NewCachedRepository(mlCache)),
		ChatDatasetRepository:                repository.NewChatDatasetRepository(cache.NewCachedRepository(mlCache)),
		ChatDatasetDocumentMappingRepository: repository.NewChatDatasetDocumentMappingRepository(cache.NewCachedRepository(mlCache)),
		SystemOpen:                           open.NewSystemOpen(c.Redis),
	}
}

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