-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathroute.ts
More file actions
204 lines (180 loc) · 5.89 KB
/
route.ts
File metadata and controls
204 lines (180 loc) · 5.89 KB
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
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
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/db/client";
import {
chatroom_invites,
chatroom_members,
users,
chatrooms,
} from "@/db/schema";
import { auth } from "@clerk/nextjs/server";
import { eq, and } from "drizzle-orm";
export async function POST(
req: Request,
context: { params: { code: string } } | Promise<{ params: { code: string } }>
) {
const { params } = await context;
try {
const { userId } = await auth();
if (!userId)
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const { code: inviteCode } = await params;
// Find the user in the DB
const user = await db
.select({
id: users.id,
firstName: users.firstName,
lastName: users.lastName,
})
.from(users)
.where(eq(users.clerkId, userId));
if (!user[0])
return NextResponse.json({ error: "User not found" }, { status: 404 });
// Find the invite
const invite = await db
.select()
.from(chatroom_invites)
.where(eq(chatroom_invites.inviteCode, inviteCode));
if (!invite[0]) {
return NextResponse.json(
{ error: "Invalid invite link" },
{ status: 404 }
);
}
// Check if invite is active
if (!invite[0].isActive) {
return NextResponse.json(
{ error: "This invite link has been deactivated" },
{ status: 400 }
);
}
// Check if invite has expired
const now = new Date();
if (invite[0].expiresAt < now) {
return NextResponse.json(
{ error: "This invite link has expired" },
{ status: 400 }
);
}
// Check if user is already a member
const existingMembership = await db
.select()
.from(chatroom_members)
.where(
and(
eq(chatroom_members.userId, user[0].id),
eq(chatroom_members.chatroomId, invite[0].chatroomId)
)
);
if (existingMembership.length > 0) {
return NextResponse.json({
success: true,
alreadyMember: true,
chatroomId: invite[0].chatroomId,
});
}
// Check maxUses if set
if (invite[0].maxUses && invite[0].usedBy) {
if (invite[0].usedBy.length >= invite[0].maxUses) {
return NextResponse.json(
{ error: "This invite link has reached its usage limit" },
{ status: 400 }
);
}
}
// Add user to chatroom with transaction for data consistency
const membershipResult = await db.transaction(async (tx) => {
// Add user to chatroom
const newMembership = await tx
.insert(chatroom_members)
.values({
userId: user[0].id,
chatroomId: invite[0].chatroomId,
role: "member",
})
.returning();
console.log(
`✅ User ${user[0].id} successfully added to chatroom ${invite[0].chatroomId} as member`
);
// Verify membership was created successfully within the transaction
const verifyMembership = await tx
.select()
.from(chatroom_members)
.where(
and(
eq(chatroom_members.userId, user[0].id),
eq(chatroom_members.chatroomId, invite[0].chatroomId)
)
);
console.log(
`🔍 Membership verification: Found ${verifyMembership.length} memberships for user ${user[0].id} in chatroom ${invite[0].chatroomId}`
);
// Update invite usage tracking within the same transaction
const currentUsedBy = invite[0].usedBy || [];
if (!currentUsedBy.includes(user[0].id)) {
await tx
.update(chatroom_invites)
.set({
usedBy: [...currentUsedBy, user[0].id],
})
.where(eq(chatroom_invites.id, invite[0].id));
}
return {
membership: newMembership[0],
verified: verifyMembership.length > 0,
};
});
// Get chatroom details for response
const chatroom = await db
.select({ name: chatrooms.name })
.from(chatrooms)
.where(eq(chatrooms.id, invite[0].chatroomId));
// Add a small delay to ensure database consistency before responding
// This helps prevent race conditions where the frontend tries to load messages
// before the membership is fully committed across all database connections
await new Promise((resolve) => setTimeout(resolve, 100));
console.log(
`🎯 Invite processing complete - User ${user[0].id} is now a verified member of chatroom ${invite[0].chatroomId}`
);
// Broadcast member join to PartyKit for real-time updates
try {
const apiKey = process.env.SHARED_PARTYKIT_BACKEND_API_KEY;
if (apiKey) {
const memberName =
user[0].firstName && user[0].lastName
? `${user[0].firstName} ${user[0].lastName}`
: user[0].firstName || user[0].lastName || "User";
await fetch(
`${process.env.NEXT_PUBLIC_PARTYKIT_HOST}/parties/main/${invite[0].chatroomId}/member-event`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
type: "member-joined",
chatroomId: invite[0].chatroomId,
member: {
id: user[0].id,
name: memberName,
role: "member",
},
timestamp: Date.now(),
}),
}
);
}
} catch (error) {
console.error("Failed to broadcast member join to PartyKit:", error);
// Don't fail the request if PartyKit broadcast fails
}
return NextResponse.json({
success: true,
chatroomId: invite[0].chatroomId,
chatroomName: chatroom[0]?.name,
});
} catch (err) {
console.error("Error processing invite:", err);
return NextResponse.json({ error: "Server error" }, { status: 500 });
}
}