forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBd962efeBurak Boduroğlu4 months ago146 commits

client.ts250 lines, 7.6 KiBHistoryRawDownload
1import type { Locale } from "@/i18n/messages";
2
3export class ApiError extends Error {
4 readonly status: number;
5 readonly retryAfter: number | null;
6
7 constructor(status: number, message: string, retryAfter: number | null = null) {
8 super(message);
9 this.name = "ApiError";
10 this.status = status;
11 this.retryAfter = retryAfter;
12 }
13}
14
15type RequestOptions = {
16 method?: "GET" | "POST" | "PATCH" | "DELETE";
17 body?: unknown;
18 signal?: AbortSignal;
19};
20
21const API_PREFIX = "/api";
22
23const API_ERROR_MESSAGES: Record<string, Record<Locale, string>> = {
24 "request failed": {
25 en: "Request failed.",
26 tr: "İşlem tamamlanamadı.",
27 },
28 "unauthorized": {
29 en: "Sign in to continue.",
30 tr: "Devam etmek için giriş yap.",
31 },
32 "forbidden": {
33 en: "You do not have permission for this action.",
34 tr: "Bu işlem için yetkin yok.",
35 },
36 "not found": {
37 en: "The requested record was not found.",
38 tr: "İstenen kayıt bulunamadı.",
39 },
40 "invalid credentials": {
41 en: "Username or password is incorrect.",
42 tr: "Kullanıcı adı veya şifre hatalı.",
43 },
44 "username already exists": {
45 en: "This username is already in use.",
46 tr: "Bu kullanıcı adı zaten kullanılıyor.",
47 },
48 "course not found": {
49 en: "Course not found.",
50 tr: "Ders bulunamadı.",
51 },
52 "exam not found": {
53 en: "Exam not found.",
54 tr: "Sınav bulunamadı.",
55 },
56 "not enrolled in this exam's course": {
57 en: "You are not enrolled in this exam's course.",
58 tr: "Bu sınavın dersine kayıtlı değilsin.",
59 },
60 "you are not enrolled in this exam's course": {
61 en: "You are not enrolled in this exam's course.",
62 tr: "Bu sınavın dersine kayıtlı değilsin.",
63 },
64 "exam is not scheduled": {
65 en: "This exam is not scheduled for online sitting.",
66 tr: "Bu sınav çevrim içi oturum için zamanlanmamış.",
67 },
68 "attempt not found": {
69 en: "Start the exam before opening the exam room.",
70 tr: "Sınav odasını açmadan önce sınavı başlat.",
71 },
72 "attempt is closed": {
73 en: "This attempt is closed. Answers are read-only.",
74 tr: "Bu oturum kapalı. Cevaplar salt okunur.",
75 },
76 "only students can sit exams": {
77 en: "Only students can take exams.",
78 tr: "Sınava yalnızca öğrenciler girebilir.",
79 },
80 "user_id: only students can be enrolled in a course": {
81 en: "Only students can be enrolled in a course.",
82 tr: "Derse yalnızca öğrenciler kaydedilebilir.",
83 },
84 "user_id: only students can be graded": {
85 en: "Only students can be graded.",
86 tr: "Yalnızca öğrencilere not verilebilir.",
87 },
88 "user_id: only students can be marked present in a lesson": {
89 en: "Only students can be marked on a lesson roll call.",
90 tr: "Ders yoklamasında yalnızca öğrenciler işaretlenebilir.",
91 },
92};
93
94function currentLocale(): Locale {
95 if (typeof window === "undefined") return "en";
96 try {
97 const saved = window.localStorage.getItem("hezarfen.locale");
98 if (saved === "en" || saved === "tr") return saved;
99 return window.navigator.language.toLowerCase().startsWith("tr") ? "tr" : "en";
100 } catch {
101 return "en";
102 }
103}
104
105function normalizeApiMessage(message: string): string {
106 return message
107 .trim()
108 .replace(/[’‘]/g, "'")
109 .replace(/\s+/g, " ")
110 .replace(/[.!?]+$/, "")
111 .toLowerCase();
112}
113
114function sentenceCase(message: string): string {
115 const trimmed = message.trim();
116 if (!trimmed) return trimmed;
117 return trimmed[0].toLocaleUpperCase("en-US") + trimmed.slice(1);
118}
119
120export async function client<T>(path: string, options: RequestOptions = {}): Promise<T> {
121 const headers: Record<string, string> = {};
122 let body: string | undefined;
123
124 if (options.body !== undefined) {
125 headers["Content-Type"] = "application/json";
126 body = JSON.stringify(options.body);
127 }
128
129 const res = await fetch(`${API_PREFIX}${path}`, {
130 method: options.method ?? "GET",
131 headers,
132 body,
133 credentials: "same-origin",
134 signal: options.signal,
135 });
136
137 if (res.status === 204) {
138 return undefined as T;
139 }
140
141 const text = await res.text();
142 let data: unknown = null;
143 if (text) {
144 try {
145 data = JSON.parse(text);
146 } catch {
147 data = { error: text };
148 }
149 }
150
151 if (!res.ok) {
152 const message =
153 data && typeof data === "object" && "error" in data && typeof (data as { error: unknown }).error === "string"
154 ? (data as { error: string }).error
155 : data && typeof data === "object" && "message" in data && typeof (data as { message: unknown }).message === "string"
156 ? (data as { message: string }).message
157 : res.statusText || "Request failed";
158
159 let retryAfter: number | null = null;
160 if (res.status === 429) {
161 const raw = res.headers.get("Retry-After");
162 if (raw) {
163 const n = Number(raw);
164 retryAfter = Number.isFinite(n) ? n : null;
165 }
166 }
167
168 throw new ApiError(res.status, message, retryAfter);
169 }
170
171 return data as T;
172}
173
174export async function formClient<T>(path: string, body: FormData, signal?: AbortSignal): Promise<T> {
175 const res = await fetch(`${API_PREFIX}${path}`, {
176 method: "POST",
177 body,
178 credentials: "same-origin",
179 signal,
180 });
181
182 const text = await res.text();
183 let data: unknown = null;
184 if (text) {
185 try {
186 data = JSON.parse(text);
187 } catch {
188 data = { error: text };
189 }
190 }
191
192 if (!res.ok) {
193 const message =
194 data && typeof data === "object" && "error" in data && typeof (data as { error: unknown }).error === "string"
195 ? (data as { error: string }).error
196 : data && typeof data === "object" && "message" in data && typeof (data as { message: unknown }).message === "string"
197 ? (data as { message: string }).message
198 : res.statusText || "Request failed";
199 throw new ApiError(res.status, message);
200 }
201
202 return data as T;
203}
204
205export async function blobClient(path: string, signal?: AbortSignal): Promise<Blob> {
206 const res = await fetch(`${API_PREFIX}${path}`, {
207 credentials: "same-origin",
208 signal,
209 });
210
211 if (!res.ok) {
212 const text = await res.text();
213 let message = res.statusText || "Request failed";
214 if (text) {
215 try {
216 const data = JSON.parse(text) as { error?: unknown; message?: unknown };
217 if (typeof data.error === "string") message = data.error;
218 else if (typeof data.message === "string") message = data.message;
219 } catch {
220 message = text;
221 }
222 }
223 throw new ApiError(res.status, message);
224 }
225
226 return res.blob();
227}
228
229export function formatApiErrorMessage(message: string, locale: Locale = currentLocale()): string {
230 const normalized = normalizeApiMessage(message);
231 const known = API_ERROR_MESSAGES[normalized]?.[locale];
232 if (known) return known;
233 if (locale === "tr") return "İşlem tamamlanamadı. Lütfen tekrar dene.";
234 return sentenceCase(message);
235}
236
237export function formatApiError(err: unknown, locale: Locale = currentLocale()): string {
238 if (err instanceof ApiError) {
239 if (err.status === 429 && err.retryAfter != null) {
240 return locale === "tr" ? `${err.retryAfter} sn sonra tekrar dene.` : `Try again in ${err.retryAfter}s.`;
241 }
242 if (err.status === 401) return API_ERROR_MESSAGES.unauthorized[locale];
243 if (err.status === 403) return API_ERROR_MESSAGES.forbidden[locale];
244 if (err.status === 404) return API_ERROR_MESSAGES["not found"][locale];
245 if (err.status >= 500) return locale === "tr" ? "Sunucuda bir sorun oluştu. Lütfen tekrar dene." : "Server error. Please try again.";
246 return formatApiErrorMessage(err.message, locale);
247 }
248 if (err instanceof Error) return formatApiErrorMessage(err.message, locale);
249 return locale === "tr" ? "Bir şeyler ters gitti." : "Something went wrong.";
250}