11package mongodb
22
33import (
4+ "sync"
5+
46 godatabases "github.com/ralvarezdev/go-databases"
57 "go.mongodb.org/mongo-driver/mongo"
68 "go.mongodb.org/mongo-driver/mongo/options"
79 "golang.org/x/net/context"
810)
911
1012type (
11- // ConnHandler interface
12- ConnHandler interface {
13- Connect () (* mongo.Client , error )
14- Client () (* mongo.Client , error )
15- Disconnect ()
16- }
17-
1813 // DefaultConnHandler struct
1914 DefaultConnHandler struct {
2015 ctx context.Context
2116 cancel context.CancelFunc
2217 clientOptions * options.ClientOptions
2318 client * mongo.Client
19+ mutex sync.Mutex
2420 }
2521)
2622
@@ -65,6 +61,10 @@ func (d *DefaultConnHandler) Connect() (*mongo.Client, error) {
6561 return nil , godatabases .ErrNilConnHandler
6662 }
6763
64+ // Lock the mutex to ensure thread safety
65+ d .mutex .Lock ()
66+ defer d .mutex .Unlock ()
67+
6868 // Check if the connection is already established
6969 if d .client != nil {
7070 return d .client , godatabases .ErrAlreadyConnected
@@ -101,6 +101,10 @@ func (d *DefaultConnHandler) Client() (*mongo.Client, error) {
101101 return nil , godatabases .ErrNilConnHandler
102102 }
103103
104+ // Lock the mutex to ensure thread safety
105+ d .mutex .Lock ()
106+ defer d .mutex .Unlock ()
107+
104108 // Check if the connection is established
105109 if d .client == nil {
106110 return nil , godatabases .ErrNotConnected
@@ -110,19 +114,31 @@ func (d *DefaultConnHandler) Client() (*mongo.Client, error) {
110114}
111115
112116// Disconnect closes the MongoDB client connection
113- func (d * DefaultConnHandler ) Disconnect () {
117+ //
118+ // Returns:
119+ //
120+ // - error: error if any
121+ func (d * DefaultConnHandler ) Disconnect () error {
114122 if d == nil {
115- return
123+ return nil
116124 }
117125
126+ // Lock the mutex to ensure thread safety
127+ d .mutex .Lock ()
128+ defer d .mutex .Unlock ()
129+
118130 // Check if the connection is established
119131 if d .client == nil {
120- return
132+ return nil
121133 }
122134
123135 // Close the connection
124136 d .cancel ()
125137 if err := d .client .Disconnect (d .ctx ); err != nil {
126- panic ( godatabases . ErrFailedToDisconnect )
138+ return err
127139 }
140+
141+ // Set the client to nil
142+ d .client = nil
143+ return nil
128144}
0 commit comments