public IActionResult ToggleFavorite(Favorite fav)
        {
            User user = userDAO.GetUser(User.Identity.Name);

            fav.UserId = user.Id;
            FavoritedByUser output = favoriteDAO.ToggleFavorite(fav.PhotoId, fav.UserId);

            return(Ok(output));
        }
Exemplo n.º 2
0
        /// <summary>
        /// Allows a user with a given userId to add a photo with a given photoId to their favorites list, or delete a previously favorited photo from the list
        /// </summary>
        /// <param name="photoId"></param>
        /// <param name="userId"></param>
        public FavoritedByUser ToggleFavorite(int photoId, int userId)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                FavoritedByUser output = new FavoritedByUser();
                // Find out if photo is already favorited by user
                SqlCommand AddOrDeleteFavorites = new SqlCommand("SELECT * FROM favorites WHERE photoId = @photoId AND userId = @userId", conn);
                AddOrDeleteFavorites.Parameters.AddWithValue("@photoId", photoId);
                AddOrDeleteFavorites.Parameters.AddWithValue("@userId", userId);

                if (AddOrDeleteFavorites.ExecuteScalar() != null)
                {
                    AddOrDeleteFavorites = new SqlCommand("DELETE favorites WHERE photoId = @photoId AND userId = @userId", conn);
                    AddOrDeleteFavorites.Parameters.AddWithValue("@photoId", photoId);
                    AddOrDeleteFavorites.Parameters.AddWithValue("@userId", userId);

                    AddOrDeleteFavorites.ExecuteNonQuery();
                }
                else
                {
                    AddOrDeleteFavorites = new SqlCommand("INSERT favorites (photoId, userId) VALUES (@photoId, @userId)", conn);
                    AddOrDeleteFavorites.Parameters.AddWithValue("@photoId", photoId);
                    AddOrDeleteFavorites.Parameters.AddWithValue("@userId", userId);

                    AddOrDeleteFavorites.ExecuteNonQuery();
                }
                output.PhotoId = photoId;

                SqlCommand Favorited = new SqlCommand("SELECT * FROM favorites WHERE photoId = @photoId and userId = @userId", conn);
                Favorited.Parameters.AddWithValue("@photoId", photoId);
                Favorited.Parameters.AddWithValue("@userId", userId);
                output.Favorited = Convert.ToBoolean(Favorited.ExecuteScalar());

                return(output);
            }
        }