template-monorepo/internal/svc/service_context.go

90 lines
2.4 KiB
Go
Raw Normal View History

2026-05-19 11:00:28 +00:00
// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package svc
import (
"context"
2026-05-19 11:00:28 +00:00
"gateway/internal/config"
redislib "gateway/internal/library/redis"
2026-05-19 12:56:32 +00:00
"gateway/internal/library/validate"
dommember "gateway/internal/model/member/domain/usecase"
memberusecase "gateway/internal/model/member/usecase"
domnotif "gateway/internal/model/notification/domain/usecase"
notifusecase "gateway/internal/model/notification/usecase"
"gateway/internal/worker/notification_retry"
2026-05-19 11:00:28 +00:00
)
type ServiceContext struct {
2026-05-19 12:56:32 +00:00
Config config.Config
Validator validate.Validate
// Redis is the process-wide client (one pool per Addr); nil when Redis.Host is empty.
Redis *redislib.Client
// Notifier is nil when Mongo is not configured (local scaffold without DB).
Notifier domnotif.NotifierUseCase
// NotificationAdmin is nil when Mongo is not configured.
NotificationAdmin domnotif.AdminNotifierUseCase
// NotificationRetry runs async delivery when Mongo + Redis are configured.
NotificationRetry *notification_retry.Runner
// MemberVerification is nil when Mongo/Redis/Notifier are not fully configured.
MemberVerification dommember.VerificationUseCase
2026-05-19 11:00:28 +00:00
}
func NewServiceContext(c config.Config) *ServiceContext {
2026-05-19 12:56:32 +00:00
v, err := validate.NewWithDefaultEN()
if err != nil {
panic(err)
}
rds, err := redislib.NewClient(c.Redis)
if err != nil {
panic(err)
}
sc := &ServiceContext{
2026-05-19 12:56:32 +00:00
Config: c,
Validator: v,
Redis: rds,
}
if c.Mongo.Host != "" {
mod, err := notifusecase.NewModuleFromParam(notifusecase.FactoryParam{
MongoConf: &c.Mongo,
Redis: rds,
Config: c.Notification,
})
if err != nil {
panic(err)
}
sc.Notifier = mod.Notifier
sc.NotificationAdmin = mod.Admin
sc.NotificationRetry = notification_retry.NewRunner(mod.RetryWorker)
}
if c.Mongo.Host != "" && rds != nil && sc.Notifier != nil {
memberMod, err := memberusecase.NewModuleFromParam(memberusecase.ModuleParam{
Redis: rds,
Notifier: sc.Notifier,
Config: c.Member,
})
if err != nil {
panic(err)
}
sc.MemberVerification = memberMod.Verification
}
return sc
}
// StartWorkers launches background workers (notification retry, etc.).
func (sc *ServiceContext) StartWorkers(ctx context.Context) {
if sc.NotificationRetry != nil {
sc.NotificationRetry.Start(ctx)
}
}
// StopWorkers waits for background workers to shut down.
func (sc *ServiceContext) StopWorkers() {
if sc.NotificationRetry != nil {
sc.NotificationRetry.Stop()
2026-05-19 11:00:28 +00:00
}
}