File size: 2,047 Bytes
32f4c77
dc5af35
 
 
f25edb3
82afc81
dc5af35
32f4c77
 
 
44bc950
32f4c77
 
 
 
44bc950
32f4c77
 
 
 
 
 
 
 
 
 
 
 
 
f25edb3
bdc8b77
32f4c77
 
44bc950
32f4c77
44bc950
 
 
 
f25edb3
 
44bc950
f25edb3
32f4c77
dc5af35
 
 
 
 
bdc8b77
dc5af35
 
 
f25edb3
82afc81
bdc8b77
82afc81
 
 
f25edb3
44bc950
f25edb3
 
 
 
 
 
 
 
bdc8b77
f25edb3
 
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
import { Request, Response } from "express";
import {
  getChatHistory,
  getRecentConversations,
  clearChat,
  getAvailableFriends,
} from "../repository/chat-repository";
import { z } from "zod";

const GetHistoryParamsSchema = z.object({
  userId: z.uuid(),
});

const GetHistoryQuerySchema = z.object({
  limit: z.coerce.number().int().min(1).max(100).default(50),
  cursor: z.uuid().optional(),
});

export async function getHistory(req: Request, res: Response) {
  const paramsResult = GetHistoryParamsSchema.safeParse(req.params);
  if (!paramsResult.success) {
    return res.status(400).json({ error: "Invalid parameters" });
  }

  const queryResult = GetHistoryQuerySchema.safeParse(req.query);
  if (!queryResult.success) {
    return res.status(400).json({ error: "Invalid query parameters" });
  }

  const { messages, user } = await getChatHistory(
    req.user.id,
    paramsResult.data.userId,
    queryResult.data.limit,
    queryResult.data.cursor,
  );

  const hasMore = messages.length === queryResult.data.limit;
  const nextCursor = hasMore ? messages[messages.length - 1].id : null;

  return res.json({
    success: true,
    data: { user, messages: messages.reverse(), nextCursor, hasMore },
  });
}

export async function getRecentConversationsHandler(
  req: Request,
  res: Response,
) {
  const conversations = await getRecentConversations(req.user.id);

  return res.json({ success: true, data: conversations });
}

export async function getAvailableFriendsHandler(req: Request, res: Response) {
  const results = await getAvailableFriends(req.user.id);
  return res.json({ success: true, data: results });
}

const ClearChatParamsSchema = z.object({
  userId: z.uuid(),
});

export async function clearChatHandler(req: Request, res: Response) {
  const paramsResult = ClearChatParamsSchema.safeParse(req.params);
  if (!paramsResult.success) {
    return res.status(400).json({ error: "Invalid parameters" });
  }

  await clearChat(req.user.id, paramsResult.data.userId);
  return res.json({ success: true });
}