NextJSNetflix/pages/api/favorite.ts

61 lines
1.9 KiB
TypeScript
Raw Permalink Normal View History

2023-08-18 13:27:23 +00:00
import prismadb from '@/lib/prismadb';
import { NextApiRequest,NextApiResponse } from "next";
import { without } from "lodash";
import serverAuth from '@/lib/serverAuth';
export default async function handler(res: NextApiResponse,req:NextApiRequest) {
try{
if (req.method === "POST"){
const { currentUser } = await serverAuth(req);
const { movieId } = req.body;
const existingMovie = await prismadb.movie.findUnique({
where: {
id: movieId,
}
});
if(!existingMovie){
throw new Error("ID Non Valido!")
}
const user = await prismadb.user.update({
where: {
email: currentUser.email || '',
},
data: {
favoriteIds: {
push: movieId,
}
}
})
return res.status(200).json(user)
}
if(req.method === "DELETE"){
const { currentUser } = await serverAuth(req);
const { movieId } = req.body;
const existingMovie = await prismadb.movie.findUnique({
where: {
id: movieId,
}
});
if(!existingMovie){
throw new Error("ID Non Valido!");
}
const updatedFavoritesId = without(currentUser.favoriteIds,movieId);
const updatedUser = await prismadb.user.update({
where: {
email: currentUser.email || '',
},
data: {
favoriteIds: {
push: updatedFavoritesId,
}
}
})
return res.status(200).json(updatedUser);
}
return res.status(405).end()
}catch(error){
console.log(error)
res.status(400).end()
}
}