Newer
Older
import { db } from "@/lib/db"
import { getCurrentUser } from "@/lib/session"
import { NextResponse } from "next/server"
import { z } from "zod"
export async function GET(request: Request) {
const { searchParams } = new URL(request.url)
const username = searchParams.get("userId") || undefined
const userIdSchema = z.string().optional()
const zod = userIdSchema.safeParse(username)
if (!zod.success) {
return NextResponse.json(zod.error, { status: 400 })
}
try {
if (type === "followers") {
const followers = await db.user
.findUnique({
where: {
username,
},
})
.followers({
include: {
followers: true,
following: true,
},
})
return NextResponse.json(followers, { status: 200 })
} else if (type === "following") {
const following = await db.user
.findUnique({
where: {
username,
},
})
.following({
include: {
followers: true,
following: true,
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
},
})
return NextResponse.json(following, { status: 200 })
}
} catch (error: any) {
return NextResponse.json(error.message, { status: 500 })
}
}
export async function PUT(request: Request) {
const session = await getCurrentUser()
const { userId } = await request.json()
const followerIdSchema = z
.object({
userId: z.string().cuid(),
})
.strict()
const zod = followerIdSchema.safeParse({ userId })
if (!zod.success) {
return NextResponse.json(zod.error, { status: 400 })
}
try {
await db.user.update({
where: {
id: userId,
},
data: {
followers: {
connect: {
id: session?.id,
},
},
},
})
return NextResponse.json(
{
message: "followed",
}, { status: 200 }
)
} catch (error: any) {
return NextResponse.json(error.message, { status: 500 })
}
}
export async function DELETE(request: Request) {
const session = await getCurrentUser()
const { userId } = await request.json()
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
const followerIdSchema = z
.object({
userId: z.string().cuid(),
})
.strict()
const zod = followerIdSchema.safeParse({ userId })
if (!zod.success) {
return NextResponse.json(zod.error, { status: 400 })
}
try {
await db.user.update({
where: {
id: userId,
},
data: {
followers: {
disconnect: {
id: session?.id,
},
},
},
})
return NextResponse.json(
{
message: "unfollowed",
}, { status: 200 },
)
} catch (error: any) {
return NextResponse.json(error.message, { status: 500 })
}
}