3900-MyRecipes-backup / Server / Controllers / LikeController.cs
LikeController.cs
Raw
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using MyRecipes2.Server.Data;
using MyRecipes2.Server.Models;
using MyRecipes2.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyRecipes2.Server.Controllers
{
    [ApiController]
    public class LikeController : ControllerBase
    {
        private readonly ApplicationDbContext dbContext;

        public LikeController(ApplicationDbContext dbContext)
        {
            this.dbContext = dbContext;
        }

        [HttpPost]
        [Route("[controller]/GetLikeInfo")]
        public bool PostHasLiked(LikeInfoRequestDto request)
        {
            return dbContext.Likes
                .Include(x => x.Recipe)
                .Include(x => x.LikedBy)
                .Where(x => x.Recipe.Id == request.RecipeId && x.LikedBy.Id == request.UserId)
                .Count() > 0;
        }

        [HttpPost]
        [Route("[controller]")]
        public void Post(CreateLikeRequestDto request)
        {
            // Find the recipe
            Recipe recipe = dbContext.Recipes
              .Where(x => x.Id == request.RecipeId)
              .Include(x => x.Likes)
              .First();
            // Find the application user
            ApplicationUser user = dbContext.Users.Where(x => x.Id == request.LikedByUserId).First();

            // Create the Like
            Like like = new();
            like.LikedBy = user;
            like.Recipe = recipe;

            // add the like to the recipe
            recipe.Likes.Add(like);

            // save the database
            dbContext.Likes.Add(like);
            dbContext.SaveChanges();
        }

        [HttpDelete]
        [Route("[controller]/{recipeId}/{userId}")]
        public void Delete(string userId, int recipeId)
        {
            // Find the recipe
            Recipe recipe = dbContext.Recipes
              .Where(x => x.Id == recipeId)
              .Include(x => x.Likes)
              .First();

            // Find the application user
            ApplicationUser user = dbContext.Users.Where(x => x.Id == userId).First();

            // Find the like
            Like like = dbContext.Likes
                .Where(x => x.Recipe == recipe && x.LikedBy == user)
                .First();

            // Remove the like from the recipe
            recipe.Likes.Remove(like);

            // save the database
            dbContext.Likes.Remove(like);
            dbContext.SaveChanges();
        }
    }
}