@@ -55,6 +55,7 @@ func buildDbURL() (*url.URL, string) {
5555 return dbUrl , dbName
5656}
5757
58+ // SetupDatabase initializes the database connection and sets up the database instance.
5859func SetupDatabase () {
5960 dbUrl , dbName := buildDbURL ()
6061 logging .Logger .Info ("Connecting to database" , "url" , dbUrl .Redacted ())
@@ -67,6 +68,8 @@ func SetupDatabase() {
6768 Db = client .Database (dbName )
6869}
6970
71+ // TeardownDatabase closes the connection to the database.
72+ // It should be called when the application is shutting down.
7073func TeardownDatabase () {
7174 if client != nil {
7275 if err := client .Disconnect (context .TODO ()); err != nil {
@@ -75,6 +78,7 @@ func TeardownDatabase() {
7578 }
7679}
7780
81+ // Get a single document from the database.
7882func Get [T any ](collection string , id primitive.ObjectID ) (* T , error ) {
7983 logging .Logger .Debug (fmt .Sprintf ("Using '%s' collection on DB" , collection ))
8084 coll := Db .Collection (collection )
@@ -212,6 +216,7 @@ func Query[T any](collectionName string, filter bson.D, sort bson.D, projection
212216 return models , nil
213217}
214218
219+ // Insert a new document into the database.
215220func Insert [T any ](collectionName string , doc T ) (primitive.ObjectID , error ) {
216221 logging .Logger .Info ("Using collection on DB" , "collectionName" , collectionName , "doc" , doc )
217222 collection := Db .Collection (collectionName )
@@ -232,6 +237,7 @@ func Insert[T any](collectionName string, doc T) (primitive.ObjectID, error) {
232237 return id , nil
233238}
234239
240+ // Update a document in the database.
235241func Update [T any ](collectionName string , id primitive.ObjectID , doc T ) (int , int , error ) {
236242 logging .Logger .Info ("Using collection on DB" , "collectionName" , collectionName , "id" , id , "doc" , doc )
237243 collection := Db .Collection (collectionName )
@@ -265,6 +271,7 @@ func Update[T any](collectionName string, id primitive.ObjectID, doc T) (int, in
265271 return int (result .MatchedCount ), int (result .ModifiedCount ), nil
266272}
267273
274+ // Delete a document from the database.
268275func Delete [T any ](collectionName string , id primitive.ObjectID ) (bool , error ) {
269276 logging .Logger .Info ("Using collection on DB" , "collectionName" , collectionName , "id" , id )
270277 collection := Db .Collection (collectionName )
0 commit comments