adding functions for getting and adding a movie
This commit is contained in:
@@ -17,7 +17,7 @@ var movieCollection *mongo.Collection = database.OpenCollection("movies")
|
|||||||
|
|
||||||
func GetMovies() gin.HandlerFunc {
|
func GetMovies() gin.HandlerFunc {
|
||||||
return func(ginCtx *gin.Context) {
|
return func(ginCtx *gin.Context) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
var movies []models.Movie
|
var movies []models.Movie
|
||||||
@@ -25,13 +25,52 @@ func GetMovies() gin.HandlerFunc {
|
|||||||
cursor, err := movieCollection.Find(ctx, bson.M{})
|
cursor, err := movieCollection.Find(ctx, bson.M{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ginCtx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to fetch movies"})
|
ginCtx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to fetch movies"})
|
||||||
|
return
|
||||||
}
|
}
|
||||||
defer cursor.Close(ctx)
|
defer cursor.Close(ctx)
|
||||||
|
|
||||||
if err = cursor.All(ctx, &movies); err != nil {
|
if err = cursor.All(ctx, &movies); err != nil {
|
||||||
ginCtx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to decode movies"})
|
ginCtx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to decode movies"})
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
ginCtx.JSON(http.StatusOK, movies)
|
ginCtx.JSON(http.StatusOK, movies)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func GetMovie() gin.HandlerFunc {
|
||||||
|
return func(ginCtx *gin.Context) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
imdbID := ginCtx.Param("imdb_id")
|
||||||
|
if imdbID == "" {
|
||||||
|
ginCtx.JSON(http.StatusBadRequest, gin.H{"error": "A valid IMDB id is required"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var movie models.Movie
|
||||||
|
|
||||||
|
err := movieCollection.FindOne(ctx, bson.M{"imdb_id": imdbID}).Decode(&movie)
|
||||||
|
if err != nil {
|
||||||
|
ginCtx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to get movie by IMDB id"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ginCtx.JSON(http.StatusOK, movie)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func AddMovie() gin.HandlersChain {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
var movie models.Movie
|
||||||
|
if err := c.ShouldBindJSON(&movie); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid input"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user