| 
									
										
										
										
											2025-08-07 13:47:42 +00:00
										 |  |  | package database | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | import ( | 
					
						
							|  |  |  | 	"context" | 
					
						
							|  |  |  | 	"time" | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	"go.mongodb.org/mongo-driver/mongo" | 
					
						
							|  |  |  | 	"go.mongodb.org/mongo-driver/mongo/options" | 
					
						
							|  |  |  | ) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | var client *mongo.Client | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-08-08 16:47:02 +00:00
										 |  |  | func Connect(uri, dbName string) (*mongo.Database, error) { | 
					
						
							| 
									
										
										
										
											2025-08-07 13:47:42 +00:00
										 |  |  | 	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) | 
					
						
							|  |  |  | 	defer cancel() | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	var err error | 
					
						
							|  |  |  | 	client, err = mongo.Connect(ctx, options.Client().ApplyURI(uri)) | 
					
						
							|  |  |  | 	if err != nil { | 
					
						
							|  |  |  | 		return nil, err | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-08-08 16:47:02 +00:00
										 |  |  | 	if err = client.Ping(ctx, nil); err != nil { | 
					
						
							| 
									
										
										
										
											2025-08-07 13:47:42 +00:00
										 |  |  | 		return nil, err | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-08-08 16:47:02 +00:00
										 |  |  | 	return client.Database(dbName), nil | 
					
						
							| 
									
										
										
										
											2025-08-07 13:47:42 +00:00
										 |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | func Disconnect() error { | 
					
						
							|  |  |  | 	if client == nil { | 
					
						
							|  |  |  | 		return nil | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | 
					
						
							|  |  |  | 	defer cancel() | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	return client.Disconnect(ctx) | 
					
						
							|  |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-28 11:46:20 +00:00
										 |  |  | func GetClient() *mongo.Client { return client } |