-
Notifications
You must be signed in to change notification settings - Fork 151
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
2e55958
commit 5d8beaa
Showing
5 changed files
with
218 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,105 @@ | ||
import { validateRequest } from "@/auth"; | ||
import prisma from "@/lib/prisma"; | ||
import { LikeInfo } from "@/lib/types"; | ||
|
||
export async function GET( | ||
req: Request, | ||
{ params: { postId } }: { params: { postId: string } }, | ||
) { | ||
try { | ||
const { user: loggedInUser } = await validateRequest(); | ||
|
||
if (!loggedInUser) { | ||
return Response.json({ error: "Unauthorized" }, { status: 401 }); | ||
} | ||
|
||
const post = await prisma.post.findUnique({ | ||
where: { id: postId }, | ||
select: { | ||
likes: { | ||
where: { | ||
userId: loggedInUser.id, | ||
}, | ||
select: { | ||
userId: true, | ||
}, | ||
}, | ||
_count: { | ||
select: { | ||
likes: true, | ||
}, | ||
}, | ||
}, | ||
}); | ||
|
||
if (!post) { | ||
return Response.json({ error: "Post not found" }, { status: 404 }); | ||
} | ||
|
||
const data: LikeInfo = { | ||
likes: post._count.likes, | ||
isLikedByUser: !!post.likes.length, | ||
}; | ||
return Response.json(data); | ||
} catch (error) { | ||
console.error(error); | ||
return Response.json({ error: "Internal server error" }, { status: 500 }); | ||
} | ||
} | ||
|
||
export async function POST( | ||
req: Request, | ||
{ params: { postId } }: { params: { postId: string } }, | ||
) { | ||
try { | ||
const { user: loggedInUser } = await validateRequest(); | ||
|
||
if (!loggedInUser) { | ||
return Response.json({ error: "Unauthorized" }, { status: 401 }); | ||
} | ||
|
||
await prisma.like.upsert({ | ||
where: { | ||
userId_postId: { | ||
userId: loggedInUser.id, | ||
postId, | ||
}, | ||
}, | ||
create: { | ||
userId: loggedInUser.id, | ||
postId, | ||
}, | ||
update: {}, | ||
}); | ||
|
||
return new Response(); | ||
} catch (error) { | ||
console.error(error); | ||
return Response.json({ error: "Internal server error" }, { status: 500 }); | ||
} | ||
} | ||
|
||
export async function DELETE( | ||
req: Request, | ||
{ params: { postId } }: { params: { postId: string } }, | ||
) { | ||
try { | ||
const { user: loggedInUser } = await validateRequest(); | ||
|
||
if (!loggedInUser) { | ||
return Response.json({ error: "Unauthorized" }, { status: 401 }); | ||
} | ||
|
||
await prisma.like.deleteMany({ | ||
where: { | ||
userId: loggedInUser.id, | ||
postId, | ||
}, | ||
}); | ||
|
||
return new Response(); | ||
} catch (error) { | ||
console.error(error); | ||
return Response.json({ error: "Internal server error" }, { status: 500 }); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
import kyInstance from "@/lib/ky"; | ||
import { LikeInfo } from "@/lib/types"; | ||
import { cn } from "@/lib/utils"; | ||
import { | ||
QueryKey, | ||
useMutation, | ||
useQuery, | ||
useQueryClient, | ||
} from "@tanstack/react-query"; | ||
import { Heart } from "lucide-react"; | ||
import { useToast } from "../ui/use-toast"; | ||
|
||
interface LikeButtonProps { | ||
postId: string; | ||
initialState: LikeInfo; | ||
} | ||
|
||
export default function LikeButton({ postId, initialState }: LikeButtonProps) { | ||
const { toast } = useToast(); | ||
|
||
const queryClient = useQueryClient(); | ||
|
||
const queryKey: QueryKey = ["like-info", postId]; | ||
|
||
const { data } = useQuery({ | ||
queryKey, | ||
queryFn: () => | ||
kyInstance.get(`/api/posts/${postId}/likes`).json<LikeInfo>(), | ||
initialData: initialState, | ||
staleTime: Infinity, | ||
}); | ||
|
||
const { mutate } = useMutation({ | ||
mutationFn: () => | ||
data.isLikedByUser | ||
? kyInstance.delete(`/api/posts/${postId}/likes`) | ||
: kyInstance.post(`/api/posts/${postId}/likes`), | ||
onMutate: async () => { | ||
await queryClient.cancelQueries({ queryKey }); | ||
|
||
const previousState = queryClient.getQueryData<LikeInfo>(queryKey); | ||
|
||
queryClient.setQueryData<LikeInfo>(queryKey, () => ({ | ||
likes: | ||
(previousState?.likes || 0) + (previousState?.isLikedByUser ? -1 : 1), | ||
isLikedByUser: !previousState?.isLikedByUser, | ||
})); | ||
|
||
return { previousState }; | ||
}, | ||
onError(error, variables, context) { | ||
queryClient.setQueryData(queryKey, context?.previousState); | ||
console.error(error); | ||
toast({ | ||
variant: "destructive", | ||
description: "Something went wrong. Please try again.", | ||
}); | ||
}, | ||
}); | ||
|
||
return ( | ||
<button onClick={() => mutate()} className="flex items-center gap-2"> | ||
<Heart | ||
className={cn( | ||
"size-5", | ||
data.isLikedByUser && "fill-red-500 text-red-500", | ||
)} | ||
/> | ||
<span className="text-sm font-medium tabular-nums"> | ||
{data.likes} <span className="hidden sm:inline">likes</span> | ||
</span> | ||
</button> | ||
); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters