4wswt4ex2: Add like and unlike for post cards
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { SESSION_COOKIE } from "@/lib/cookie";
|
||||
import { setPostLike } from "@/lib/post-like";
|
||||
|
||||
// POST /api/posts/:id/like -> feed POST /api/v1/posts/{id}/like
|
||||
// DELETE /api/posts/:id/like -> feed DELETE /api/v1/posts/{id}/like
|
||||
// No request body. Returns { isLiked, likesCount }; likesCount is null when the
|
||||
// feed response carries no count. 401 { error: "sign_in" } without a session.
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
type Ctx = { params: Promise<{ id: string }> };
|
||||
|
||||
async function handle(req: NextRequest, ctx: Ctx, liked: boolean) {
|
||||
const sessionId = req.cookies.get(SESSION_COOKIE)?.value;
|
||||
const { id } = await ctx.params;
|
||||
const result = await setPostLike(sessionId, id, liked);
|
||||
if (!result.ok) {
|
||||
return NextResponse.json({ error: result.error }, { status: result.status });
|
||||
}
|
||||
return NextResponse.json({ isLiked: result.isLiked, likesCount: result.likesCount });
|
||||
}
|
||||
|
||||
export function POST(req: NextRequest, ctx: Ctx) {
|
||||
return handle(req, ctx, true);
|
||||
}
|
||||
|
||||
export function DELETE(req: NextRequest, ctx: Ctx) {
|
||||
return handle(req, ctx, false);
|
||||
}
|
||||
@@ -35,3 +35,10 @@ button:disabled { opacity: .5; cursor: not-allowed; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
.new-posts { position: sticky; top: 68px; z-index: 4; align-self: center; margin: 0; padding: 8px 16px; border-radius: 999px; }
|
||||
.sentinel { height: 1px; }
|
||||
.like-btn { display: inline-flex; align-items: center; gap: 6px; margin: 0; padding: 4px 8px; background: transparent; color: var(--grey); border-radius: 8px; font-size: 14px; font-weight: 400; }
|
||||
.like-btn:hover:not(:disabled) { color: var(--red); background: #fff3f3; }
|
||||
.like-btn.liked { color: var(--red); }
|
||||
.like-btn:disabled { opacity: 1; cursor: default; }
|
||||
.like-btn:disabled:not(.liked) { color: var(--grey); }
|
||||
.like-error { color: #a8141b; font-size: 13px; align-self: center; }
|
||||
.post-stats { align-items: center; }
|
||||
|
||||
Reference in New Issue
Block a user