61 lines
1.9 KiB
TypeScript
61 lines
1.9 KiB
TypeScript
|
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()
|
||
|
}
|
||
|
}
|