Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { NextResponse } from "next/server";
import { z } from "zod";
import { db } from "@/lib/db";
// get gweets
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const type = searchParams.get("type") || undefined;
const id = searchParams.get("id") || undefined;
const cursorQuery = searchParams.get("cursor") || undefined;
const take = Number(searchParams.get("limit")) || 20;
const skip = cursorQuery ? 1 : 0;
const cursor = cursorQuery ? { id: cursorQuery } : undefined;
try {
const gweets = await db.gweet.findMany({
skip,
take,
cursor,
where: {
...(type === "comments" && {
replyToGweetId: id,
}),
...(type === "search" && {
text: {
contains: id,
mode: "insensitive",
},
}),
...(type === "user_gweets" && {
}),
...(type === "user_replies" && {
NOT: {
replyToGweetId: null,
},
}),
...(type === "user_likes" && {
likes: {
some: {
userId: id,
},
},
}),
},
include: {
media: true,
regweets: true,
quote: {
include: {
author: true,
media: true,
},
},
},
orderBy: {
createdAt: "desc",
},
});
const nextId = gweets.length < take ? undefined : gweets[gweets.length - 1].id;
return NextResponse.json({ gweets, nextId });
} catch (error) {
return NextResponse.error();
}
}
// create gweet
export async function POST(request: Request) {
const gweet = await request.json();
const gweetSchema = z
.object({
content: z.string().min(1).max(280),
authorId: z.string().cuid(),
replyToGweetId: z.string().cuid().optional(),
quoteGweetId: z.string().cuid().optional(),
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
})
.strict();
const zod = gweetSchema.safeParse(gweet);
if (!zod.success) {
return NextResponse.json(
{
message: "Invalid request body",
error: zod.error.formErrors,
}, { status: 400 },
);
}
try {
const created_gweet = await db.gweet.create({
data: {
...gweet,
},
});
return NextResponse.json(created_gweet, { status: 200 });
} catch (error: any) {
return NextResponse.json(
{
message: "Something went wrong",
error: error.message,
}, { status: error.errorCode || 500 },
);
}
}
// delete gweet
export async function DELETE(request: Request) {
const { searchParams } = new URL(request.url);
const id = searchParams.get("id") as string;
const idSchema = z.string().cuid();
const zod = idSchema.safeParse(id);
if (!zod.success) {
return NextResponse.json(
{
message: "Invalid request body",
error: zod.error.formErrors,
}, { status: 400 },
);
}
try {
await db.gweet.delete({
where: {
id,
},
});
return NextResponse.json({ message: "Gweet deleted successfully", });
} catch (error: any) {
return NextResponse.json(
{
message: "Something went wrong",
error: error.message,
}, { status: error.errorCode || 500 },
);
}
}