refactor: Update user service to use sync.Once for singleton initialization

This commit is contained in:
Marvin Zhang
2024-07-29 12:39:56 +08:00
parent ea5ec117cc
commit 01332490d3

View File

@@ -1,6 +1,7 @@
package user package user
import ( import (
"github.com/apex/log"
"github.com/crawlab-team/crawlab/core/constants" "github.com/crawlab-team/crawlab/core/constants"
"github.com/crawlab-team/crawlab/core/errors" "github.com/crawlab-team/crawlab/core/errors"
"github.com/crawlab-team/crawlab/core/interfaces" "github.com/crawlab-team/crawlab/core/interfaces"
@@ -14,6 +15,7 @@ import (
"go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo"
"sync"
"time" "time"
) )
@@ -181,7 +183,7 @@ func (svc *ServiceV2) getSecretFunc() jwt.Keyfunc {
} }
} }
func NewUserServiceV2() (svc *ServiceV2, err error) { func newUserServiceV2() (svc *ServiceV2, err error) {
// service // service
svc = &ServiceV2{ svc = &ServiceV2{
modelSvc: service.NewModelServiceV2[models.UserV2](), modelSvc: service.NewModelServiceV2[models.UserV2](),
@@ -191,6 +193,7 @@ func NewUserServiceV2() (svc *ServiceV2, err error) {
// initialize // initialize
if err := svc.Init(); err != nil { if err := svc.Init(); err != nil {
log.Errorf("failed to initialize user service: %v", err)
return nil, trace.TraceError(err) return nil, trace.TraceError(err)
} }
@@ -198,15 +201,14 @@ func NewUserServiceV2() (svc *ServiceV2, err error) {
} }
var userSvcV2 *ServiceV2 var userSvcV2 *ServiceV2
var userSvcV2Once sync.Once
func GetUserServiceV2() (svc *ServiceV2, err error) { func GetUserServiceV2() (svc *ServiceV2, err error) {
if userSvcV2 != nil { userSvcV2Once.Do(func() {
return userSvcV2, nil userSvcV2, err = newUserServiceV2()
}
svc, err = NewUserServiceV2()
if err != nil { if err != nil {
return nil, err return
} }
userSvcV2 = svc })
return svc, nil return userSvcV2, nil
} }