code refactor

This commit is contained in:
MaysWind
2025-08-04 20:43:33 +08:00
parent d35e127b9e
commit 84523d8b8a
18 changed files with 163 additions and 95 deletions
+2 -2
View File
@@ -81,13 +81,13 @@ func sendTestMail(c *core.CliContext) error {
return err
}
if !config.EnableSMTP || mail.Container.Current == nil {
if !config.EnableSMTP {
return errs.ErrSMTPServerNotEnabled
}
toAddress := c.String("to")
err = mail.Container.Current.SendMail(&mail.MailMessage{
err = mail.Container.SendMail(&mail.MailMessage{
To: toAddress,
Subject: "ezBookkeeping test e-mail",
Body: "This is a test e-mail",
+1 -1
View File
@@ -79,7 +79,7 @@ func startWebServer(c *core.CliContext) error {
return err
}
serverInfo := fmt.Sprintf("current server id is %d, current instance id is %d", requestid.Container.Current.GetCurrentServerUniqId(), requestid.Container.Current.GetCurrentInstanceUniqId())
serverInfo := fmt.Sprintf("current server id is %d, current instance id is %d", requestid.Container.GetCurrentServerUniqId(), requestid.Container.GetCurrentInstanceUniqId())
uuidServerInfo := ""
if config.UuidGeneratorType == settings.InternalUuidGeneratorType {
uuidServerInfo = fmt.Sprintf(", current uuid server id is %d", config.UuidServerId)
+10 -10
View File
@@ -23,7 +23,7 @@ type ApiUsingConfig struct {
// CurrentConfig returns the current config
func (a *ApiUsingConfig) CurrentConfig() *settings.Config {
return a.container.Current
return a.container.GetCurrentConfig()
}
// GetTransactionPictureInfoResponse returns the view-object of transaction picture basic info according to the transaction picture model
@@ -53,15 +53,15 @@ func (a *ApiUsingConfig) GetAfterRegisterNotificationContent(userLanguage string
language = clientLanguage
}
if !a.container.Current.AfterRegisterNotification.Enabled {
if !a.CurrentConfig().AfterRegisterNotification.Enabled {
return ""
}
if multiLanguageContent, exists := a.container.Current.AfterRegisterNotification.MultiLanguageContent[language]; exists {
if multiLanguageContent, exists := a.CurrentConfig().AfterRegisterNotification.MultiLanguageContent[language]; exists {
return multiLanguageContent
}
return a.container.Current.AfterRegisterNotification.DefaultContent
return a.CurrentConfig().AfterRegisterNotification.DefaultContent
}
// GetAfterLoginNotificationContent returns the notification content displayed each time users log in
@@ -72,15 +72,15 @@ func (a *ApiUsingConfig) GetAfterLoginNotificationContent(userLanguage string, c
language = clientLanguage
}
if !a.container.Current.AfterLoginNotification.Enabled {
if !a.CurrentConfig().AfterLoginNotification.Enabled {
return ""
}
if multiLanguageContent, exists := a.container.Current.AfterLoginNotification.MultiLanguageContent[language]; exists {
if multiLanguageContent, exists := a.CurrentConfig().AfterLoginNotification.MultiLanguageContent[language]; exists {
return multiLanguageContent
}
return a.container.Current.AfterLoginNotification.DefaultContent
return a.CurrentConfig().AfterLoginNotification.DefaultContent
}
// GetAfterOpenNotificationContent returns the notification content displayed each time users open the app
@@ -91,15 +91,15 @@ func (a *ApiUsingConfig) GetAfterOpenNotificationContent(userLanguage string, cl
language = clientLanguage
}
if !a.container.Current.AfterOpenNotification.Enabled {
if !a.CurrentConfig().AfterOpenNotification.Enabled {
return ""
}
if multiLanguageContent, exists := a.container.Current.AfterOpenNotification.MultiLanguageContent[language]; exists {
if multiLanguageContent, exists := a.CurrentConfig().AfterOpenNotification.MultiLanguageContent[language]; exists {
return multiLanguageContent
}
return a.container.Current.AfterOpenNotification.DefaultContent
return a.CurrentConfig().AfterOpenNotification.DefaultContent
}
// ApiUsingDuplicateChecker represents an api that need to use duplicate checker
+1 -7
View File
@@ -30,13 +30,7 @@ var (
// LatestExchangeRateHandler returns latest exchange rate data
func (a *ExchangeRatesApi) LatestExchangeRateHandler(c *core.WebContext) (any, *errs.Error) {
dataSource := exchangerates.Container.Current
if dataSource == nil {
return nil, errs.ErrInvalidExchangeRatesDataSource
}
exchangeRateResponse, err := dataSource.GetLatestExchangeRates(c, c.GetCurrentUid(), a.container.Current)
exchangeRateResponse, err := exchangerates.Container.GetLatestExchangeRates(c, c.GetCurrentUid(), a.CurrentConfig())
if err != nil {
return nil, errs.Or(err, errs.ErrOperationFailed)
+9 -5
View File
@@ -9,7 +9,7 @@ import (
// AvatarProviderContainer contains the current user avatar provider
type AvatarProviderContainer struct {
Current AvatarProvider
current AvatarProvider
}
// Initialize a user avatar provider container singleton instance
@@ -20,13 +20,13 @@ var (
// InitializeAvatarProvider initializes the current user avatar provider according to the config
func InitializeAvatarProvider(config *settings.Config) error {
if config.AvatarProvider == core.USER_AVATAR_PROVIDER_INTERNAL {
Container.Current = NewInternalStorageAvatarProvider(config)
Container.current = NewInternalStorageAvatarProvider(config)
return nil
} else if config.AvatarProvider == core.USER_AVATAR_PROVIDER_GRAVATAR {
Container.Current = NewGravatarAvatarProvider()
Container.current = NewGravatarAvatarProvider()
return nil
} else if config.AvatarProvider == "" {
Container.Current = NewNullAvatarProvider()
Container.current = NewNullAvatarProvider()
return nil
}
@@ -35,5 +35,9 @@ func InitializeAvatarProvider(config *settings.Config) error {
// GetAvatarUrl returns the avatar url by the current user avatar provider
func (p *AvatarProviderContainer) GetAvatarUrl(user *models.User) string {
return p.Current.GetAvatarUrl(user)
if p.current == nil {
return ""
}
return p.current.GetAvatarUrl(user)
}
+1 -1
View File
@@ -9,5 +9,5 @@ type CliUsingConfig struct {
// CurrentConfig returns the current config
func (l *CliUsingConfig) CurrentConfig() *settings.Config {
return l.container.Current
return l.container.GetCurrentConfig()
}
+1 -1
View File
@@ -95,7 +95,7 @@ func TestCronJobSchedulerContainerRepeatRun(t *testing.T) {
InMemoryDuplicateCheckerCleanupIntervalDuration: 60 * time.Second,
})
duplicatechecker.Container.Current = checker
duplicatechecker.SetDuplicateChecker(checker)
container := &CronJobSchedulerContainer{
allJobsMap: make(map[string]*CronJob),
+1 -1
View File
@@ -22,7 +22,7 @@ func (j *CronJob) doRun() {
start := time.Now()
c := core.NewCronJobContext(j.Name, j.Period.GetInterval())
if duplicatechecker.Container.Current != nil {
if duplicatechecker.Container.IsEnabled() {
localAddr, err := utils.GetLocalIPAddressesString()
if err != nil {
@@ -9,7 +9,7 @@ import (
// DuplicateCheckerContainer contains the current duplicate checker
type DuplicateCheckerContainer struct {
Current DuplicateChecker
current DuplicateChecker
}
// Initialize a duplicate checker container singleton instance
@@ -21,7 +21,7 @@ var (
func InitializeDuplicateChecker(config *settings.Config) error {
if config.DuplicateCheckerType == settings.InMemoryDuplicateCheckerType {
checker, err := NewInMemoryDuplicateChecker(config)
Container.Current = checker
Container.current = checker
return err
}
@@ -29,37 +29,75 @@ func InitializeDuplicateChecker(config *settings.Config) error {
return errs.ErrInvalidDuplicateCheckerType
}
// SetDuplicateChecker sets the current duplicate checker
func SetDuplicateChecker(checker DuplicateChecker) {
Container.current = checker
}
// IsEnabled returns whether the duplicate checker is enabled
func (c *DuplicateCheckerContainer) IsEnabled() bool {
return c.current != nil
}
// GetSubmissionRemark returns whether the same submission has been processed and related remark by the current duplicate checker
func (c *DuplicateCheckerContainer) GetSubmissionRemark(checkerType DuplicateCheckerType, uid int64, identification string) (bool, string) {
return c.Current.GetSubmissionRemark(checkerType, uid, identification)
if c.current == nil {
return false, ""
}
return c.current.GetSubmissionRemark(checkerType, uid, identification)
}
// SetSubmissionRemark saves the identification and remark by the current duplicate checker
func (c *DuplicateCheckerContainer) SetSubmissionRemark(checkerType DuplicateCheckerType, uid int64, identification string, remark string) {
c.Current.SetSubmissionRemark(checkerType, uid, identification, remark)
if c.current == nil {
return
}
c.current.SetSubmissionRemark(checkerType, uid, identification, remark)
}
// RemoveSubmissionRemark removes the identification and remark by the current duplicate checker
func (c *DuplicateCheckerContainer) RemoveSubmissionRemark(checkerType DuplicateCheckerType, uid int64, identification string) {
c.Current.RemoveSubmissionRemark(checkerType, uid, identification)
if c.current == nil {
return
}
c.current.RemoveSubmissionRemark(checkerType, uid, identification)
}
// GetOrSetCronJobRunningInfo returns the running info when the cron job is running or saves the running info by the current duplicate checker
func (c *DuplicateCheckerContainer) GetOrSetCronJobRunningInfo(jobName string, runningInfo string, runningInterval time.Duration) (bool, string) {
return c.Current.GetOrSetCronJobRunningInfo(jobName, runningInfo, runningInterval)
if c.current == nil {
return false, ""
}
return c.current.GetOrSetCronJobRunningInfo(jobName, runningInfo, runningInterval)
}
// RemoveCronJobRunningInfo removes the running info of the cron job by the current duplicate checker
func (c *DuplicateCheckerContainer) RemoveCronJobRunningInfo(jobName string) {
c.Current.RemoveCronJobRunningInfo(jobName)
if c.current == nil {
return
}
c.current.RemoveCronJobRunningInfo(jobName)
}
// GetFailureCount returns the failure count of the specified failure key
func (c *DuplicateCheckerContainer) GetFailureCount(failureKey string) uint32 {
return c.Current.GetFailureCount(failureKey)
if c.current == nil {
return 0
}
return c.current.GetFailureCount(failureKey)
}
// IncreaseFailureCount increases the failure count of the specified failure key
func (c *DuplicateCheckerContainer) IncreaseFailureCount(failureKey string) uint32 {
return c.Current.IncreaseFailureCount(failureKey)
if c.current == nil {
return 0
}
return c.current.IncreaseFailureCount(failureKey)
}
@@ -1,13 +1,15 @@
package exchangerates
import (
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/errs"
"github.com/mayswind/ezbookkeeping/pkg/models"
"github.com/mayswind/ezbookkeeping/pkg/settings"
)
// ExchangeRatesDataSourceContainer contains the current exchange rates data source
type ExchangeRatesDataSourceContainer struct {
Current ExchangeRatesDataSource
current ExchangeRatesDataSource
}
// Initialize a exchange rates data source container singleton instance
@@ -18,60 +20,69 @@ var (
// InitializeExchangeRatesDataSource initializes the current exchange rates data source according to the config
func InitializeExchangeRatesDataSource(config *settings.Config) error {
if config.ExchangeRatesDataSource == settings.ReserveBankOfAustraliaDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&ReserveBankOfAustraliaDataSource{})
Container.current = newCommonHttpExchangeRatesDataSource(&ReserveBankOfAustraliaDataSource{})
return nil
} else if config.ExchangeRatesDataSource == settings.BankOfCanadaDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&BankOfCanadaDataSource{})
Container.current = newCommonHttpExchangeRatesDataSource(&BankOfCanadaDataSource{})
return nil
} else if config.ExchangeRatesDataSource == settings.CzechNationalBankDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&CzechNationalBankDataSource{})
Container.current = newCommonHttpExchangeRatesDataSource(&CzechNationalBankDataSource{})
return nil
} else if config.ExchangeRatesDataSource == settings.DanmarksNationalbankDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&DanmarksNationalbankDataSource{})
Container.current = newCommonHttpExchangeRatesDataSource(&DanmarksNationalbankDataSource{})
return nil
} else if config.ExchangeRatesDataSource == settings.EuroCentralBankDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&EuroCentralBankDataSource{})
Container.current = newCommonHttpExchangeRatesDataSource(&EuroCentralBankDataSource{})
return nil
} else if config.ExchangeRatesDataSource == settings.NationalBankOfGeorgiaDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&NationalBankOfGeorgiaDataSource{})
Container.current = newCommonHttpExchangeRatesDataSource(&NationalBankOfGeorgiaDataSource{})
return nil
} else if config.ExchangeRatesDataSource == settings.CentralBankOfHungaryDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&CentralBankOfHungaryDataSource{})
Container.current = newCommonHttpExchangeRatesDataSource(&CentralBankOfHungaryDataSource{})
return nil
} else if config.ExchangeRatesDataSource == settings.BankOfIsraelDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&BankOfIsraelDataSource{})
Container.current = newCommonHttpExchangeRatesDataSource(&BankOfIsraelDataSource{})
return nil
} else if config.ExchangeRatesDataSource == settings.CentralBankOfMyanmarDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&CentralBankOfMyanmarDataSource{})
Container.current = newCommonHttpExchangeRatesDataSource(&CentralBankOfMyanmarDataSource{})
return nil
} else if config.ExchangeRatesDataSource == settings.NorgesBankDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&NorgesBankDataSource{})
Container.current = newCommonHttpExchangeRatesDataSource(&NorgesBankDataSource{})
return nil
} else if config.ExchangeRatesDataSource == settings.NationalBankOfPolandDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&NationalBankOfPolandDataSource{})
Container.current = newCommonHttpExchangeRatesDataSource(&NationalBankOfPolandDataSource{})
return nil
} else if config.ExchangeRatesDataSource == settings.NationalBankOfRomaniaDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&NationalBankOfRomaniaDataSource{})
Container.current = newCommonHttpExchangeRatesDataSource(&NationalBankOfRomaniaDataSource{})
return nil
} else if config.ExchangeRatesDataSource == settings.BankOfRussiaDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&BankOfRussiaDataSource{})
Container.current = newCommonHttpExchangeRatesDataSource(&BankOfRussiaDataSource{})
return nil
} else if config.ExchangeRatesDataSource == settings.SwissNationalBankDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&SwissNationalBankDataSource{})
Container.current = newCommonHttpExchangeRatesDataSource(&SwissNationalBankDataSource{})
return nil
} else if config.ExchangeRatesDataSource == settings.NationalBankOfUkraineDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&NationalBankOfUkraineDataSource{})
Container.current = newCommonHttpExchangeRatesDataSource(&NationalBankOfUkraineDataSource{})
return nil
} else if config.ExchangeRatesDataSource == settings.CentralBankOfUzbekistanDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&CentralBankOfUzbekistanDataSource{})
Container.current = newCommonHttpExchangeRatesDataSource(&CentralBankOfUzbekistanDataSource{})
return nil
} else if config.ExchangeRatesDataSource == settings.InternationalMonetaryFundDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&InternationalMonetaryFundDataSource{})
Container.current = newCommonHttpExchangeRatesDataSource(&InternationalMonetaryFundDataSource{})
return nil
} else if config.ExchangeRatesDataSource == settings.UserCustomExchangeRatesDataSource {
Container.Current = newUserCustomExchangeRatesDataSource()
Container.current = newUserCustomExchangeRatesDataSource()
return nil
}
return errs.ErrInvalidExchangeRatesDataSource
}
// GetLatestExchangeRates returns the latest exchange rates data from the current exchange rates data source
func (e *ExchangeRatesDataSourceContainer) GetLatestExchangeRates(c core.Context, uid int64, currentConfig *settings.Config) (*models.LatestExchangeRateResponse, error) {
if Container.current == nil {
return nil, errs.ErrInvalidExchangeRatesDataSource
}
return e.current.GetLatestExchangeRates(c, uid, currentConfig)
}
@@ -326,15 +326,12 @@ func executeLatestExchangeRateHandler(t *testing.T, dataSourceType string) *mode
err := InitializeExchangeRatesDataSource(config)
assert.Nil(t, err)
dataSource := Container.Current
assert.NotNil(t, dataSource)
ginContext, _ := gin.CreateTestContext(httptest.NewRecorder())
context := &core.WebContext{
Context: ginContext,
}
exchangeRateResponse, err := dataSource.GetLatestExchangeRates(context, context.GetCurrentUid(), config)
exchangeRateResponse, err := Container.GetLatestExchangeRates(context, context.GetCurrentUid(), config)
assert.Nil(t, err)
assert.NotNil(t, exchangeRateResponse)
+10 -5
View File
@@ -1,12 +1,13 @@
package mail
import (
"github.com/mayswind/ezbookkeeping/pkg/errs"
"github.com/mayswind/ezbookkeeping/pkg/settings"
)
// MailerContainer contains the current mailer
type MailerContainer struct {
Current Mailer
current Mailer
}
// Initialize a mailer container singleton instance
@@ -17,7 +18,7 @@ var (
// InitializeMailer initializes the current mailer according to the config
func InitializeMailer(config *settings.Config) error {
if !config.EnableSMTP {
Container.Current = nil
Container.current = nil
return nil
}
@@ -27,11 +28,15 @@ func InitializeMailer(config *settings.Config) error {
return err
}
Container.Current = mailer
Container.current = mailer
return nil
}
// SendMail sends an email according to argument
func (u *MailerContainer) SendMail(message *MailMessage) error {
return u.Current.SendMail(message)
func (m *MailerContainer) SendMail(message *MailMessage) error {
if m.current == nil {
return errs.ErrSMTPServerNotEnabled
}
return m.current.SendMail(message)
}
@@ -68,13 +68,7 @@ func (h *mcpQueryLatestExchangeRatesToolHandler) Handle(c *core.WebContext, call
return nil, nil, errs.ErrIncompleteOrIncorrectSubmission
}
dataSource := exchangerates.Container.Current
if dataSource == nil {
return nil, nil, errs.ErrInvalidExchangeRatesDataSource
}
exchangeRateResponse, err := dataSource.GetLatestExchangeRates(c, user.Uid, currentConfig)
exchangeRateResponse, err := exchangerates.Container.GetLatestExchangeRates(c, user.Uid, currentConfig)
if err != nil {
return nil, nil, err
+1 -6
View File
@@ -11,12 +11,7 @@ const requestIdHeader = "X-Request-ID"
// RequestId generates a new request id and add it to context and response header
func RequestId(config *settings.Config) core.MiddlewareHandlerFunc {
return func(c *core.WebContext) {
if requestid.Container.Current == nil {
c.Next()
return
}
requestId := requestid.Container.Current.GenerateRequestId(c.ClientIP(), c.ClientPort())
requestId := requestid.Container.GenerateRequestId(c.ClientIP(), c.ClientPort())
c.SetContextId(requestId)
if config.EnableRequestIdHeader {
+26 -4
View File
@@ -7,7 +7,7 @@ import (
// RequestIdContainer contains the current request id generator
type RequestIdContainer struct {
Current RequestIdGenerator
current RequestIdGenerator
}
// Initialize a request id container singleton instance
@@ -23,11 +23,33 @@ func InitializeRequestIdGenerator(c core.Context, config *settings.Config) error
return err
}
Container.Current = generator
Container.current = generator
return nil
}
// GenerateRequestId returns a new request id by the current request id generator
func (u *RequestIdContainer) GenerateRequestId(clientIpAddr string, clientPort uint16) string {
return u.Current.GenerateRequestId(clientIpAddr, clientPort)
func (r *RequestIdContainer) GenerateRequestId(clientIpAddr string, clientPort uint16) string {
if r.current == nil {
return ""
}
return r.current.GenerateRequestId(clientIpAddr, clientPort)
}
// GetCurrentServerUniqId returns current server unique id
func (r *RequestIdContainer) GetCurrentServerUniqId() uint16 {
if r.current == nil {
return 0
}
return r.current.GetCurrentServerUniqId()
}
// GetCurrentInstanceUniqId returns current application instance unique id
func (r *RequestIdContainer) GetCurrentInstanceUniqId() uint16 {
if r.current == nil {
return 0
}
return r.current.GetCurrentInstanceUniqId()
}
+2 -7
View File
@@ -6,7 +6,6 @@ import (
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/datastore"
"github.com/mayswind/ezbookkeeping/pkg/errs"
"github.com/mayswind/ezbookkeeping/pkg/mail"
"github.com/mayswind/ezbookkeeping/pkg/settings"
"github.com/mayswind/ezbookkeeping/pkg/storage"
@@ -61,7 +60,7 @@ type ServiceUsingConfig struct {
// CurrentConfig returns the current config
func (s *ServiceUsingConfig) CurrentConfig() *settings.Config {
return s.container.Current
return s.container.GetCurrentConfig()
}
// ServiceUsingMailer represents a service that need to use mailer
@@ -71,11 +70,7 @@ type ServiceUsingMailer struct {
// SendMail sends an email according to argument
func (s *ServiceUsingMailer) SendMail(message *mail.MailMessage) error {
if s.container.Current == nil {
return errs.ErrSMTPServerNotEnabled
}
return s.container.Current.SendMail(message)
return s.container.SendMail(message)
}
// ServiceUsingUuid represents a service that need to use uuid
+7 -2
View File
@@ -2,7 +2,7 @@ package settings
// ConfigContainer contains the current setting config
type ConfigContainer struct {
Current *Config
current *Config
}
// Initialize a config container singleton instance
@@ -15,5 +15,10 @@ var (
// SetCurrentConfig sets the current config by a given config
func SetCurrentConfig(config *Config) {
Container.Current = config
Container.current = config
}
// GetCurrentConfig returns the current config
func (c *ConfigContainer) GetCurrentConfig() *Config {
return c.current
}
+12 -4
View File
@@ -7,7 +7,7 @@ import (
// UuidContainer contains the current uuid generator
type UuidContainer struct {
Current UuidGenerator
current UuidGenerator
}
// Initialize a uuid container singleton instance
@@ -19,7 +19,7 @@ var (
func InitializeUuidGenerator(config *settings.Config) error {
if config.UuidGeneratorType == settings.InternalUuidGeneratorType {
generator, err := NewInternalUuidGenerator(config)
Container.Current = generator
Container.current = generator
return err
}
@@ -29,10 +29,18 @@ func InitializeUuidGenerator(config *settings.Config) error {
// GenerateUuid returns a new uuid by the current uuid generator
func (u *UuidContainer) GenerateUuid(uuidType UuidType) int64 {
return u.Current.GenerateUuid(uuidType)
if u.current == nil {
return 0
}
return u.current.GenerateUuid(uuidType)
}
// GenerateUuids returns new uuids by the current uuid generator
func (u *UuidContainer) GenerateUuids(uuidType UuidType, count uint16) []int64 {
return u.Current.GenerateUuids(uuidType, count)
if u.current == nil {
return nil
}
return u.current.GenerateUuids(uuidType, count)
}