-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsupportClient.ts
More file actions
102 lines (94 loc) · 2.52 KB
/
Copy pathsupportClient.ts
File metadata and controls
102 lines (94 loc) · 2.52 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
import { buildApiUrl } from "./_base";
export type SupportMessageDto = {
id: string;
thread_id: string;
role: "user" | "staff";
content: string;
created_at: string;
};
export type SupportThreadDto = {
id: string;
username: string;
created_at: string;
updated_at: string;
unread_for_staff?: boolean;
unread_for_user?: boolean;
unread_for_user_count?: number;
last_preview?: string | null;
};
async function parseJson<T>(res: Response): Promise<T & { ok?: boolean; error?: string }> {
try {
return (await res.json()) as T & { ok?: boolean; error?: string };
} catch {
return { ok: false, error: `Invalid response (${res.status})` } as T & {
ok?: boolean;
error?: string;
};
}
}
export async function fetchMySupportChat(opts?: {
markRead?: boolean;
}): Promise<{
ok: boolean;
thread?: SupportThreadDto;
messages?: SupportMessageDto[];
error?: string;
}> {
const qs = opts?.markRead ? "?markRead=1" : "";
const res = await fetch(buildApiUrl(`/api/support${qs}`), {
method: "GET",
credentials: "include",
});
return parseJson(res);
}
export async function sendSupportUserMessage(content: string): Promise<{
ok: boolean;
message?: SupportMessageDto;
error?: string;
}> {
const res = await fetch(buildApiUrl("/api/support"), {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ action: "send", content }),
});
return parseJson(res);
}
export async function fetchStaffSupportThreads(): Promise<{
ok: boolean;
threads?: SupportThreadDto[];
error?: string;
}> {
const res = await fetch(buildApiUrl("/api/support?staff=1"), {
method: "GET",
credentials: "include",
});
return parseJson(res);
}
export async function fetchStaffSupportThread(threadId: string): Promise<{
ok: boolean;
thread?: SupportThreadDto;
messages?: SupportMessageDto[];
error?: string;
}> {
const res = await fetch(
buildApiUrl(`/api/support?staff=1&threadId=${encodeURIComponent(threadId)}`),
{
method: "GET",
credentials: "include",
},
);
return parseJson(res);
}
export async function sendStaffSupportReply(
threadId: string,
content: string,
): Promise<{ ok: boolean; message?: SupportMessageDto; error?: string }> {
const res = await fetch(buildApiUrl("/api/support"), {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ action: "staff_reply", threadId, content }),
});
return parseJson(res);
}