Newer
Older
import { NextResponse } from "next/server";
import { z } from "zod";
import { db } from "@/lib/db";
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const user_id = searchParams.get("user_id") || undefined;
const userIdSchema = z.string().cuid();
const zod = userIdSchema.safeParse(user_id);
if (!zod.success) {
return NextResponse.json(
{
message: "Invalid request body",
error: zod.error.formErrors,
}, { status: 400 },
);
}
try {
const gweets = await db.gweet.findMany({
where: {
likes: {
some: {
userId: user_id,
},
},
},
include: {
author: true,
media: true,
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
allComments: true,
},
});
return NextResponse.json(gweets, { status: 200 });
} catch (error: any) {
return NextResponse.json(
{
message: "Something went wrong",
error: error.message,
}, { status: error.errorCode || 500 },
);
}
}
// like and dislike
export async function POST(request: Request) {
const { gweet_id, user_id } = await request.json();
const likeSchema = z
.object({
gweet_id: z.string().cuid(),
user_id: z.string().cuid(),
})
.strict();
const zod = likeSchema.safeParse({ gweet_id, user_id });
if (!zod.success) {
return NextResponse.json(
{
message: "Invalid request body",
error: zod.error.formErrors,
}, { status: 400 },
);
}
try {
const like = await db.like.findFirst({
where: {
gweetId: gweet_id,
userId: user_id,
},
});
if (like) {
await db.like.delete({
where: {
id: like.id,
},
});
return NextResponse.json({ message: "Gweet unliked" });
} else {
await db.like.create({
data: {
gweetId: gweet_id,
userId: user_id,
},
});
return NextResponse.json({ message: "Gweet liked" });
}
} catch (error: any) {
return NextResponse.json({
message: "Something went wrong",
error: error.message,
});
}