From 3b64c256813271471c116948bd318b43a218bdea Mon Sep 17 00:00:00 2001 From: Florian Sylvain Date: Fri, 14 Oct 2022 23:38:50 +0200 Subject: [PATCH] Fixed get responses and push/getDocs --- internal/articles.go | 4 ++++ internal/database.go | 16 ++++++++-------- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/internal/articles.go b/internal/articles.go index 994b54b..fba0d7b 100644 --- a/internal/articles.go +++ b/internal/articles.go @@ -22,16 +22,19 @@ func AddArticle(c *gin.Context) { var article Article if c.BindJSON(&article) != nil { SendErrorMessageToClient(c, "Could not correctly parse the article.") + return } document, err := bson.Marshal(article) if err != nil { SendErrorMessageToClient(c, "could not correctly marshal the article") + return } err = pushDocument(ARTICLES_LOCATION, document) if err != nil { SendErrorMessageToClient(c, "could not insert document into DB") + return } SendOkMessageToClient(c, "Article successfully added!") @@ -43,6 +46,7 @@ func GetAllArticles(c *gin.Context) { documents, err := getDocuments(ARTICLES_LOCATION, bson.D{}) if err != nil { SendErrorMessageToClient(c, err.Error()) + return } for i := 0; i < len(documents); i++ { diff --git a/internal/database.go b/internal/database.go index 82c0976..a5fc5c3 100644 --- a/internal/database.go +++ b/internal/database.go @@ -23,14 +23,11 @@ func getNewClient() *mongo.Client { return client } -func getCollection(location Location) *mongo.Collection { - client := getNewClient() - defer client.Disconnect(context.TODO()) - return client.Database(location.Database).Collection(location.Collection) -} - func pushDocument(location Location, document interface{}) error { - collection := getCollection(location) + client := getNewClient() + collection := client.Database(location.Database).Collection(location.Collection) + defer client.Disconnect(context.TODO()) + _, err := collection.InsertOne(context.TODO(), document) if err != nil { return err @@ -39,7 +36,10 @@ func pushDocument(location Location, document interface{}) error { } func getDocuments(location Location, filter interface{}) ([][]byte, error) { - collection := getCollection(location) + client := getNewClient() + collection := client.Database(location.Database).Collection(location.Collection) + defer client.Disconnect(context.TODO()) + var results [][]byte cursor, err := collection.Find(context.TODO(), filter)