From 154e2d20fbd3c2583c1c8c6d7bfa609e59b86c5f Mon Sep 17 00:00:00 2001 From: Florian Sylvain Date: Tue, 20 Dec 2022 02:31:10 +0100 Subject: [PATCH] getUniqueDocument implementation --- internal/articlesHandlers.go | 8 ++------ internal/database.go | 12 ++++++++++++ 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/internal/articlesHandlers.go b/internal/articlesHandlers.go index 94f7b8f..c870aff 100644 --- a/internal/articlesHandlers.go +++ b/internal/articlesHandlers.go @@ -19,18 +19,14 @@ func GetAllArticlesHandler(c *gin.Context) { func GetArticleHandler(c *gin.Context) { articleID := c.Params.ByName("id") - articles, err := getDocuments(articlesLocation, + article, err := getUniqueDocument(articlesLocation, bson.D{{Key: "id_name", Value: articleID}}) if err != nil { - SendBadRequest(c, err.Error()) - return - } - if len(articles) == 0 { SendBadRequest(c, "The ID provided doesn't match any article.") return } var parsedArticle Article - bson.Unmarshal(articles[0], &parsedArticle) + bson.Unmarshal(article, &parsedArticle) c.JSON(http.StatusOK, parsedArticle) } diff --git a/internal/database.go b/internal/database.go index b05be88..da6e592 100644 --- a/internal/database.go +++ b/internal/database.go @@ -52,6 +52,18 @@ func getDocuments(location Location, filter interface{}) ([][]byte, error) { return results, nil } +func getUniqueDocument(location Location, filter interface{}) ([]byte, error) { + client := getNewClient() + collection := client.Database(location.Database).Collection(location.Collection) + defer client.Disconnect(context.TODO()) + + singleResult := collection.FindOne(context.TODO(), filter) + if singleResult.Err() != nil { + return nil, errors.New("no document was found, check the filter or the location.") + } + return singleResult.DecodeBytes() +} + func deleteDocument(location Location, filter interface{}) (int64, error) { client := getNewClient() collection := client.Database(location.Database).Collection(location.Collection)