Skip to content

Commit 8b0b31d

Browse files
fix(authActions): enhance error handling in registerUser function for better feedback
fix(messageActions): update getMessagesByContainer to allow dynamic limit and fix cursor comparison fix(MessageTable): pass loadMoreLimit prop to useMessages for consistent message loading fix(page): adjust message loading logic to utilize loadMoreLimit for pagination fix(useMessages): refactor loadMore function to improve cursor handling and message retrieval fix(util): improve error handling in handleFormServerErrors for root-level server errors
1 parent 81f8280 commit 8b0b31d

File tree

7 files changed

+75
-30
lines changed

7 files changed

+75
-30
lines changed

src/app/actions/authActions.ts

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { LoginSchema } from '@/lib/schemas/LoginSchema';
77
import { combinedRegisterSchema, ProfileSchema, registerSchema, RegisterSchema } from '@/lib/schemas/RegisterSchema';
88
import { deleteTokenById, generateToken, getTokenByToken } from '@/lib/tokens';
99
import { ActionResult } from '@/types';
10-
import { User } from '@prisma/client';
10+
import { Prisma, User } from '@prisma/client';
1111
import bcrypt from 'bcryptjs';
1212
import { AuthError } from 'next-auth';
1313

@@ -114,8 +114,35 @@ export async function registerUser(data:RegisterSchema): Promise<ActionResult<Us
114114

115115

116116
}catch(error){
117-
console.error( error);
118-
return{status: 'error', error: 'Something went wrong'}
117+
console.error('registerUser failed', error);
118+
119+
if (error instanceof Prisma.PrismaClientKnownRequestError) {
120+
if (error.code === 'P2002') {
121+
const target = Array.isArray(error.meta?.target)
122+
? error.meta.target.map((item) => String(item))
123+
: [];
124+
125+
if (target.includes('email')) {
126+
return {
127+
status: 'error',
128+
error: [
129+
{
130+
code: 'custom',
131+
message: 'Email is already registered',
132+
path: ['email']
133+
}
134+
]
135+
}
136+
}
137+
}
138+
}
139+
140+
const message = error instanceof Error ? error.message : 'Unknown error';
141+
142+
return {
143+
status: 'error',
144+
error: shouldExposeError ? message : 'Something went wrong'
145+
}
119146
}
120147
}
121148

src/app/actions/messageActions.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ export async function getMessageThread(recipientId: string) {
222222
}
223223

224224

225-
export async function getMessagesByContainer(container?: string|null,cursor?:string, limit=4){
225+
export async function getMessagesByContainer(container?: string|null,cursor?:string, limit=5){
226226

227227
try {
228228

@@ -231,7 +231,7 @@ export async function getMessagesByContainer(container?: string|null,cursor?:str
231231
const conditions = {
232232
[container ==='outbox'? 'senderId': 'recipientId']: userId,
233233
...(container === 'outbox'? {senderDeleted: false}:{recipientDeleted:false} ),
234-
...(cursor? {created: {lte:new Date(cursor)}} : {})
234+
...(cursor? {created: {lt:new Date(cursor)}} : {})
235235

236236
}
237237

src/app/favicon.ico

201 KB
Binary file not shown.

src/app/messages/MessageTable.tsx

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import MessageTableCell from "./MessageTableCell";
2424
type Props = {
2525
initialMessages: MessageDto[];
2626
nextCursor?: string;
27+
loadMoreLimit?: number;
2728
};
2829

2930
const outboxColumns = [
@@ -42,10 +43,11 @@ const inboxColumns = [
4243

4344
export default function MessageTable({ initialMessages,
4445
nextCursor,
46+
loadMoreLimit,
4547
}: Props) {
4648

4749

48-
const {columns, isOutbox, isDeleting, deleteMessage, selectRow, messages, loadMore, loadingMore, hasMore}= useMessages(initialMessages, nextCursor);
50+
const {columns, isOutbox, isDeleting, deleteMessage, selectRow, messages, loadMore, loadingMore, hasMore}= useMessages(initialMessages, nextCursor, loadMoreLimit);
4951

5052

5153

src/app/messages/page.tsx

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,18 @@ export default async function MessagesPage({
1010
}: {
1111
searchParams: Promise<{ container?: string }>;
1212
}) {
13+
const INITIAL_MESSAGES_LIMIT = 5;
14+
const LOAD_MORE_MESSAGES_LIMIT = 2;
15+
1316
const { container } = await searchParams;
1417
const normalizedContainer =
1518
container === "outbox" ? "outbox" : "inbox";
1619

1720

1821
const {messages, nextCursor} = await getMessagesByContainer(
19-
normalizedContainer
22+
normalizedContainer,
23+
undefined,
24+
INITIAL_MESSAGES_LIMIT
2025
);
2126

2227

@@ -34,7 +39,11 @@ export default async function MessagesPage({
3439

3540
<div className="col-span-10">
3641

37-
<MessageTable initialMessages={messages} nextCursor={nextCursor} />
42+
<MessageTable
43+
initialMessages={messages}
44+
nextCursor={nextCursor}
45+
loadMoreLimit={LOAD_MORE_MESSAGES_LIMIT}
46+
/>
3847
</div>
3948
</div>
4049
);

src/hooks/useMessages.tsx

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ const inboxColumns = [
2727

2828
export const useMessages = (
2929
initialMessages: MessageDto[],
30-
nextCursor?: string
30+
nextCursor?: string,
31+
loadMoreLimit = 2
3132
) => {
3233
const set = useMessageStore((state) => state.set);
3334
const remove = useMessageStore((state) => state.remove);
@@ -39,13 +40,11 @@ export const useMessages = (
3940
(state) => state.resetMessages
4041
);
4142

42-
43-
const cursorRef = useRef(nextCursor);
44-
45-
4643
const searchParams = useSearchParams();
4744
const router = useRouter();
4845
const container = searchParams.get("container");
46+
const normalizedContainer =
47+
container === "outbox" ? "outbox" : "inbox";
4948
const isOutbox =
5049
searchParams.get("container") === "outbox";
5150
const [isDeleting, setDeleting] = useState({
@@ -54,30 +53,33 @@ export const useMessages = (
5453
});
5554

5655
const [loadingMore, setLoadingMore] = useState(false);
56+
const [cursor, setCursor] = useState(nextCursor);
5757

5858
useEffect(() => {
59+
resetMessages();
5960
set(initialMessages);
60-
61-
return () => {
62-
resetMessages();
63-
};
64-
}, [initialMessages, resetMessages, set]);
61+
setCursor(nextCursor);
62+
}, [initialMessages, nextCursor, normalizedContainer, resetMessages, set]);
6563

6664

6765
const loadMore = useCallback(async () => {
68-
if(cursorRef.current){
66+
if(cursor){
6967
setLoadingMore(true);
70-
const {messages, nextCursor} =
71-
await getMessagesByContainer(
72-
container,
73-
cursorRef.current
74-
);
75-
76-
set(messages);
77-
cursorRef.current = nextCursor;
78-
setLoadingMore(false);
68+
try {
69+
const {messages, nextCursor} =
70+
await getMessagesByContainer(
71+
normalizedContainer,
72+
cursor,
73+
loadMoreLimit
74+
);
75+
76+
set(messages);
77+
setCursor(nextCursor);
78+
} finally {
79+
setLoadingMore(false);
80+
}
7981
}
80-
}, [container, set]);
82+
}, [cursor, loadMoreLimit, normalizedContainer, set]);
8183

8284

8385

@@ -122,6 +124,6 @@ const loadMore = useCallback(async () => {
122124
messages,
123125
loadingMore,
124126
loadMore,
125-
hasMore:!!cursorRef.current,
127+
hasMore:!!cursor,
126128
};
127129
};

src/lib/util.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,11 @@ export function handleFormServerErrors<TFieldValues extends FieldValues>(
2121
if (Array.isArray(errorResponse.error)) {
2222

2323
errorResponse.error.forEach((e) => {
24+
if (e.path.length === 0) {
25+
setError('root.serverError', { message: e.message });
26+
return;
27+
}
28+
2429
const fieldName = e.path.join('.') as Path<TFieldValues>
2530
setError(fieldName, { message: e.message })
2631

0 commit comments

Comments
 (0)