92 lines
2.3 KiB
Go
92 lines
2.3 KiB
Go
package controllers
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/captbrogers/MagicStreamServer/database"
|
|
"github.com/captbrogers/MagicStreamServer/models"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/go-playground/validator/v10"
|
|
"go.mongodb.org/mongo-driver/v2/bson"
|
|
"go.mongodb.org/mongo-driver/v2/mongo"
|
|
)
|
|
|
|
var movieCollection *mongo.Collection = database.OpenCollection("movies")
|
|
|
|
var validate = validator.New()
|
|
|
|
func GetMovies() gin.HandlerFunc {
|
|
return func(ginCtx *gin.Context) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
|
|
var movies []models.Movie
|
|
|
|
cursor, err := movieCollection.Find(ctx, bson.M{})
|
|
if err != nil {
|
|
ginCtx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to fetch movies"})
|
|
return
|
|
}
|
|
defer cursor.Close(ctx)
|
|
|
|
if err = cursor.All(ctx, &movies); err != nil {
|
|
ginCtx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to decode movies"})
|
|
return
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
if err := validate.Struct(movie); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Validation failed when binding struct", "details": err.Error()})
|
|
return
|
|
}
|
|
|
|
result, err := movieCollection.InsertOne(ctx, movie)
|
|
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to insert the movie"})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusCreated, result)
|
|
}
|
|
} |