Fetch All User Reviews
Learn how to implement a function that retrieves user reviews.
We'll cover the following...
Setting up the controller
Assume that the user has a profile page where they can view all of their prior movie reviews. Such a page would require an endpoint to retrieve all the reviews where the reviewer_id
matches.
// Allow a user view all their Reviewsfunc AllUserReviews() gin.HandlerFunc {return func(c *gin.Context) {var searchreviews []models.ReviewsreviewId := c.Param("reviewer_id")//defer cancel()i,erro:= strconv.Atoi(reviewId)if erro != nil {// Handle error}if reviewId == "" {log.Println("No reviewer id passed")c.Header("Content-Type", "application/json")c.JSON(http.StatusNotFound, gin.H{"Error": "Invalid Search Index"})c.Abort()return}var ctx, cancel = context.WithTimeout(context.Background(), 100*time.Second)defer cancel()searchquerydb, err := reviewCollection.Find(ctx, bson.M{"reviewer_id":i})if err != nil {c.IndentedJSON(404, "something went wrong in fetching the dbquery")return}err = searchquerydb.All(ctx, &searchreviews)if err != nil {log.Println(err)c.IndentedJSON(400, "invalid")return}defer searchquerydb.Close(ctx)if err := searchquerydb.Err(); err != nil {log.Println(err)c.IndentedJSON(400, "invalid request")return}defer cancel()c.IndentedJSON(200, searchreviews)}}
The reviewControllers.go file
...