forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB7122d71Burak Boduroğlu4 months ago419 commits

client.ts512 lines, 19.1 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 cache?: RequestCache;
20};
21
22const API_PREFIX = "/api";
23
24// Deadline for a JSON request. Generous enough for the slowest real call
25// (login's Argon2 hash under load), short enough that a hung socket surfaces
26// as an error instead of a permanently disabled button.
27const REQUEST_TIMEOUT_MS = 20_000;
28
29const API_ERROR_MESSAGES: Record<string, Record<Locale, string>> = {
30 // Settings lists reject two entries that fold to the same word — İZİN/izin,
31 // ÖDEV/odev. Keyed on the whole normalized string, so both fields are listed.
32 "exam_kinds: two entries are the same word apart from upper/lower case or turkish letters — keep only one of them": {
33 en: "Two exam kinds are the same word apart from upper/lower case or Turkish letters. Keep only one of them.",
34 tr: "İki sınav türü, büyük/küçük harf veya Türkçe harf farkı dışında aynı. Sadece birini bırak.",
35 },
36 "attendance_statuses: two entries are the same word apart from upper/lower case or turkish letters — keep only one of them": {
37 en: "Two attendance statuses are the same word apart from upper/lower case or Turkish letters. Keep only one of them.",
38 tr: "İki yoklama durumu, büyük/küçük harf veya Türkçe harf farkı dışında aynı. Sadece birini bırak.",
39 },
40 "request failed": {
41 en: "Request failed.",
42 tr: "İşlem tamamlanamadı.",
43 },
44 "unauthorized": {
45 en: "Sign in to continue.",
46 tr: "Devam etmek için giriş yap.",
47 },
48 "forbidden": {
49 en: "You do not have permission for this action.",
50 tr: "Bu işlem için yetkin yok.",
51 },
52 "not found": {
53 en: "The requested record was not found.",
54 tr: "İstenen kayıt bulunamadı.",
55 },
56 "invalid credentials": {
57 en: "Username or password is incorrect.",
58 tr: "Kullanıcı adı veya şifre hatalı.",
59 },
60 "username already exists": {
61 en: "This username is already in use.",
62 tr: "Bu kullanıcı adı zaten kullanılıyor.",
63 },
64 "file too large": {
65 en: "This file is larger than the allowed upload limit.",
66 tr: "Bu dosya izin verilen yükleme sınırından büyük.",
67 },
68 "payload too large": {
69 en: "This upload is too large. Choose a smaller file and try again.",
70 tr: "Bu yükleme çok büyük. Daha küçük bir dosya seçip tekrar dene.",
71 },
72 "request entity too large": {
73 en: "This upload is too large. Choose a smaller file and try again.",
74 tr: "Bu yükleme çok büyük. Daha küçük bir dosya seçip tekrar dene.",
75 },
76 "unsupported file type": {
77 en: "This file type is not supported.",
78 tr: "Bu dosya türü desteklenmiyor.",
79 },
80 "unsupported image type": {
81 en: "This image type is not supported. Use PNG, JPEG, WebP, or GIF.",
82 tr: "Bu görsel türü desteklenmiyor. PNG, JPEG, WebP veya GIF kullan.",
83 },
84 "invalid image": {
85 en: "The image could not be read. Choose another image and try again.",
86 tr: "Görsel okunamadı. Başka bir görsel seçip tekrar dene.",
87 },
88 "too many files": {
89 en: "This note already has the maximum number of files.",
90 tr: "Bu notta en fazla dosya sayısına ulaşılmış.",
91 },
92 "note file limit reached": {
93 en: "This note already has the maximum number of files.",
94 tr: "Bu notta en fazla dosya sayısına ulaşılmış.",
95 },
96 "this time overlaps a slot you have already published": {
97 en: "This time overlaps a slot you already published.",
98 tr: "Bu zaman aralığı, daha önce yayınladığın bir müsaitlikle çakışıyor.",
99 },
100 "a repeated slot overlaps one you have already published": {
101 en: "One of the repeated slots overlaps a slot you already published.",
102 tr: "Tekrarlanan müsaitliklerden biri, daha önce yayınladığın bir müsaitlikle çakışıyor.",
103 },
104 "the repeated slots overlap each other": {
105 en: "The repeated slots overlap each other.",
106 tr: "Tekrarlanan müsaitlikler birbiriyle çakışıyor.",
107 },
108 // Booking/decision conflicts from domain/appointment.rs — byte-exact.
109 "the slot is already booked": {
110 en: "Someone else booked this time first.",
111 tr: "Bu saati senden önce başkası aldı.",
112 },
113 "the slot has already started": {
114 en: "This time has already started, so it can no longer be booked.",
115 tr: "Bu saat başladığı için artık randevu alınamaz.",
116 },
117 "you already have an appointment at that time": {
118 en: "You already have an appointment at that time.",
119 tr: "O saatte zaten bir randevun var.",
120 },
121 "the appointment is already settled": {
122 en: "This appointment is already settled.",
123 tr: "Bu randevu zaten sonuçlanmış.",
124 },
125 "the appointment has already started": {
126 en: "This appointment has already started.",
127 tr: "Bu randevu çoktan başladı.",
128 },
129 "that time has already started": {
130 en: "That time has already started. Pick a later one.",
131 tr: "O saat çoktan başladı. Daha ileri bir saat seç.",
132 },
133 "no time has been proposed": {
134 en: "No time has been proposed for this appointment yet.",
135 tr: "Bu randevu için henüz bir saat önerilmedi.",
136 },
137 "the appointment is no longer pending": {
138 en: "This appointment is no longer waiting for an answer.",
139 tr: "Bu randevu artık yanıt bekliyor değil.",
140 },
141 "question: this question did not come from a bank template": {
142 en: "This question was not copied from a bank template, so there is nothing to refresh it from.",
143 tr: "Bu soru bir banka şablonundan kopyalanmadığı için yenilenecek bir kaynağı yok.",
144 },
145 "request timed out": {
146 en: "The server did not respond in time. Check your connection and try again.",
147 tr: "Sunucu zamanında yanıt vermedi. Bağlantını kontrol edip tekrar dene.",
148 },
149 "only the template's owner or an admin can change it": {
150 en: "Only the teacher who created this template (or an admin) can change it.",
151 tr: "Bu şablonu yalnızca onu oluşturan öğretmen (veya bir yönetici) değiştirebilir.",
152 },
153 "only the course creator, an assigned teacher, or a manager/admin can author questions": {
154 en: "Only this course's teachers or a manager can add questions to this exam.",
155 tr: "Bu sınava yalnızca dersin öğretmenleri veya bir müdür soru ekleyebilir.",
156 },
157 "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank": {
158 en: "Only this course's teachers or a manager can save this question to the bank.",
159 tr: "Bu soruyu bankaya yalnızca dersin öğretmenleri veya bir müdür kaydedebilir.",
160 },
161 "cannot change questions after attempts have started": {
162 en: "Students have already started this exam, so its questions can no longer change.",
163 tr: "Öğrenciler bu sınava başladığı için soruları artık değiştirilemez.",
164 },
165 "bank questions still reference this subject — re-tag or delete them first": {
166 en: "Question bank templates still use this subject. Re-tag or delete them first.",
167 tr: "Soru bankasındaki şablonlar hâlâ bu konuyu kullanıyor. Önce onları başka konuya taşı veya sil.",
168 },
169 "course not found": {
170 en: "Course not found.",
171 tr: "Ders bulunamadı.",
172 },
173 "exam not found": {
174 en: "Exam not found.",
175 tr: "Sınav bulunamadı.",
176 },
177 "not enrolled in this exam's course": {
178 en: "You are not enrolled in this exam's course.",
179 tr: "Bu sınavın dersine kayıtlı değilsin.",
180 },
181 "you are not enrolled in this exam's course": {
182 en: "You are not enrolled in this exam's course.",
183 tr: "Bu sınavın dersine kayıtlı değilsin.",
184 },
185 "exam is not scheduled": {
186 en: "This exam is not scheduled for online sitting.",
187 tr: "Bu sınav çevrim içi oturum için zamanlanmamış.",
188 },
189 "attempt not found": {
190 en: "Start the exam before opening the exam room.",
191 tr: "Sınav odasını açmadan önce sınavı başlat.",
192 },
193 "attempt is closed": {
194 en: "This attempt is closed. Answers are read-only.",
195 tr: "Bu oturum kapalı. Cevaplar salt okunur.",
196 },
197 "exam has not started": {
198 en: "This exam has not started yet.",
199 tr: "Bu sınav henüz başlamadı.",
200 },
201 "exam has ended": {
202 en: "This exam has ended.",
203 tr: "Bu sınav sona erdi.",
204 },
205 "no attempts left": {
206 en: "No attempts left for this exam.",
207 tr: "Bu sınav için deneme hakkı kalmadı.",
208 },
209 "answer is required": {
210 en: "Enter an answer before saving.",
211 tr: "Kaydetmeden önce cevap gir.",
212 },
213 "only students can sit exams": {
214 en: "Only students can take exams.",
215 tr: "Sınava yalnızca öğrenciler girebilir.",
216 },
217 "user_id: only students can be enrolled in a course": {
218 en: "Only students can be enrolled in a course.",
219 tr: "Derse yalnızca öğrenciler kaydedilebilir.",
220 },
221 "user_id: only students can be graded": {
222 en: "Only students can be graded.",
223 tr: "Yalnızca öğrencilere not verilebilir.",
224 },
225 "user_id: only students can be marked present in a lesson": {
226 en: "Only students can be marked on a lesson roll call.",
227 tr: "Ders yoklamasında yalnızca öğrenciler işaretlenebilir.",
228 },
229 "event is full": {
230 en: "This event is full.",
231 tr: "Bu etkinlik dolu.",
232 },
233 "registration is closed": {
234 en: "Registration is closed for this event.",
235 tr: "Bu etkinlik için kayıt kapalı.",
236 },
237 "already registered": {
238 en: "This student is already registered.",
239 tr: "Bu öğrenci zaten kayıtlı.",
240 },
241 "already enrolled": {
242 en: "This student is already enrolled.",
243 tr: "Bu öğrenci zaten kayıtlı.",
244 },
245 "active pomodoro session already exists": {
246 en: "You already have a focus session running.",
247 tr: "Zaten devam eden bir odak oturumun var.",
248 },
249 "no active pomodoro session": {
250 en: "There is no active focus session to finish.",
251 tr: "Bitirilecek aktif odak oturumu yok.",
252 },
253};
254
255const FIELD_LABELS: Record<string, Record<Locale, string>> = {
256 content: { en: "Content", tr: "İçerik" },
257 description: { en: "Description", tr: "Açıklama" },
258 password: { en: "Password", tr: "Şifre" },
259 title: { en: "Title", tr: "Başlık" },
260 username: { en: "Username", tr: "Kullanıcı adı" },
261};
262
263export function currentLocale(): Locale {
264 if (typeof window === "undefined") return "en";
265 try {
266 const saved = window.localStorage.getItem("hezarfen.locale");
267 if (saved === "en" || saved === "tr") return saved;
268 return window.navigator.language.toLowerCase().startsWith("tr") ? "tr" : "en";
269 } catch {
270 return "en";
271 }
272}
273
274function normalizeApiMessage(message: string): string {
275 return message
276 .trim()
277 .replace(/[’‘]/g, "'")
278 .replace(/\s+/g, " ")
279 .replace(/[.!?]+$/, "")
280 .toLowerCase();
281}
282
283function sentenceCase(message: string): string {
284 const trimmed = message.trim();
285 if (!trimmed) return trimmed;
286 return trimmed[0].toLocaleUpperCase("en-US") + trimmed.slice(1);
287}
288
289function formatRuntimeErrorMessage(message: string, locale: Locale): string | null {
290 const normalized = normalizeApiMessage(message);
291 if (/^(failed to fetch|load failed|networkerror|network request failed)/.test(normalized)) {
292 return locale === "tr"
293 ? "Sunucuya ulaşılamadı. Bağlantını kontrol edip tekrar dene."
294 : "Could not reach the server. Check your connection and try again.";
295 }
296 if (
297 /^(typeerror:\s*)?cannot (read|set) propert(y|ies) of (null|undefined)/.test(normalized) ||
298 /^use\w+ must be used within \w+provider/.test(normalized)
299 ) {
300 return locale === "tr"
301 ? "Sayfa yüklenirken bir sorun oluştu. Sayfayı yeniden yükleyip tekrar dene."
302 : "Something went wrong while loading the page. Reload the page and try again.";
303 }
304 return null;
305}
306
307function formatNumber(value: string, locale: Locale): string {
308 return new Intl.NumberFormat(locale === "tr" ? "tr-TR" : "en-US").format(Number(value));
309}
310
311function fieldLabel(field: string, locale: Locale): string {
312 const normalized = field.trim().toLowerCase().replace(/[_.-]+/g, " ");
313 const known = FIELD_LABELS[normalized]?.[locale];
314 if (known) return known;
315 return sentenceCase(normalized);
316}
317
318function formatValidationMessage(message: string, locale: Locale): string | null {
319 const lengthMatch = message.match(/^([\w .-]+) must be at most (\d+) characters \(got (\d+)\)$/i);
320 if (!lengthMatch) return null;
321
322 const label = fieldLabel(lengthMatch[1], locale);
323 const max = formatNumber(lengthMatch[2], locale);
324 const got = formatNumber(lengthMatch[3], locale);
325
326 if (locale === "tr") return `${label} en fazla ${max} karakter olmalı. Şu an ${got} karakter.`;
327 return `${label} must be at most ${max} characters. Currently ${got} characters.`;
328}
329
330function errorMessageFromPayload(data: unknown, fallback: string): string {
331 if (!data || typeof data !== "object") return fallback;
332 const record = data as Record<string, unknown>;
333 if (typeof record.error === "string") return record.error;
334 if (typeof record.message === "string") return record.message;
335 const detail = record.detail;
336 if (typeof detail === "string") return detail;
337 if (Array.isArray(detail)) {
338 return detail
339 .map((item) => {
340 if (!item || typeof item !== "object") return "";
341 const row = item as Record<string, unknown>;
342 const loc = Array.isArray(row.loc) ? row.loc.map(String).join(".") : "";
343 const msg = typeof row.msg === "string" ? row.msg : "";
344 return loc && msg ? `${loc}: ${msg}` : msg;
345 })
346 .filter(Boolean)
347 .join("; ") || fallback;
348 }
349 return fallback;
350}
351
352export async function client<T>(path: string, options: RequestOptions = {}): Promise<T> {
353 const headers: Record<string, string> = {};
354 let body: string | undefined;
355
356 if (options.body !== undefined) {
357 headers["Content-Type"] = "application/json";
358 body = JSON.stringify(options.body);
359 }
360
361 // JSON calls only — uploads (formClient) and downloads (blobClient) stay
362 // untimed. Without this a dead connection leaves callers (exam-room REST
363 // autosave) stuck on "saving…" until the browser gives up.
364 const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
365 // Caller-initiated aborts keep their original AbortError so cancellation
366 // handling upstream is untouched; only our own deadline becomes an ApiError.
367 const asDeadlineError = (err: unknown) =>
368 timeout.aborted && !options.signal?.aborted ? new ApiError(408, "request timed out") : err;
369
370 let res: Response;
371 try {
372 res = await fetch(`${API_PREFIX}${path}`, {
373 method: options.method ?? "GET",
374 headers,
375 body,
376 credentials: "same-origin",
377 signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout,
378 cache: options.cache,
379 });
380 } catch (err) {
381 throw asDeadlineError(err);
382 }
383
384 if (res.status === 204) {
385 return undefined as T;
386 }
387
388 // The deadline aborts the body stream too, so headers can arrive in time and
389 // res.text() still blow up mid-download on a multi-MB response.
390 let text: string;
391 try {
392 text = await res.text();
393 } catch (err) {
394 throw asDeadlineError(err);
395 }
396
397 let data: unknown = null;
398 if (text) {
399 try {
400 data = JSON.parse(text);
401 } catch {
402 data = { error: text };
403 }
404 }
405
406 if (!res.ok) {
407 const message = errorMessageFromPayload(data, res.statusText || "Request failed");
408
409 let retryAfter: number | null = null;
410 if (res.status === 429 || res.status === 503) {
411 const raw = res.headers.get("Retry-After");
412 if (raw) {
413 const n = Number(raw);
414 retryAfter = Number.isFinite(n) ? n : null;
415 }
416 }
417
418 throw new ApiError(res.status, message, retryAfter);
419 }
420
421 return data as T;
422}
423
424export async function formClient<T>(path: string, body: FormData, signal?: AbortSignal): Promise<T> {
425 const res = await fetch(`${API_PREFIX}${path}`, {
426 method: "POST",
427 body,
428 credentials: "same-origin",
429 signal,
430 });
431
432 const text = await res.text();
433 let data: unknown = null;
434 if (text) {
435 try {
436 data = JSON.parse(text);
437 } catch {
438 data = { error: text };
439 }
440 }
441
442 if (!res.ok) {
443 const message = errorMessageFromPayload(data, res.statusText || "Request failed");
444 throw new ApiError(res.status, message);
445 }
446
447 return data as T;
448}
449
450export async function blobClient(path: string, signal?: AbortSignal): Promise<Blob> {
451 const res = await fetch(`${API_PREFIX}${path}`, {
452 credentials: "same-origin",
453 signal,
454 });
455
456 if (!res.ok) {
457 const text = await res.text();
458 let message = res.statusText || "Request failed";
459 if (text) {
460 try {
461 message = errorMessageFromPayload(JSON.parse(text), message);
462 } catch {
463 message = text;
464 }
465 }
466 throw new ApiError(res.status, message);
467 }
468
469 return res.blob();
470}
471
472export function formatApiErrorMessage(message: string, locale: Locale = currentLocale()): string {
473 const normalized = normalizeApiMessage(message);
474 const known = API_ERROR_MESSAGES[normalized]?.[locale];
475 if (known) return known;
476 const runtime = formatRuntimeErrorMessage(message, locale);
477 if (runtime) return runtime;
478 const validation = formatValidationMessage(message, locale);
479 if (validation) return validation;
480 // Unmapped backend text is raw English/technical — never surface it to the
481 // user. Fall back to a clean localized line; add a mapping in
482 // API_ERROR_MESSAGES when a specific message deserves its own wording.
483 return locale === "tr"
484 ? "İşlem tamamlanamadı. Lütfen bilgileri kontrol edip tekrar dene."
485 : "Something went wrong. Please check your input and try again.";
486}
487
488export function formatApiError(err: unknown, locale: Locale = currentLocale()): string {
489 if (err instanceof ApiError) {
490 if ((err.status === 429 || err.status === 503) && err.retryAfter != null) {
491 return locale === "tr" ? `${err.retryAfter} sn sonra tekrar dene.` : `Try again in ${err.retryAfter}s.`;
492 }
493 // The specific backend message wins over the per-status generic one —
494 // otherwise every 401/403/404/413/5xx entry in the table is dead code.
495 const known = API_ERROR_MESSAGES[normalizeApiMessage(err.message)]?.[locale];
496 if (known) return known;
497 if (err.status === 401) return API_ERROR_MESSAGES.unauthorized[locale];
498 if (err.status === 403) return API_ERROR_MESSAGES.forbidden[locale];
499 if (err.status === 404) return API_ERROR_MESSAGES["not found"][locale];
500 if (err.status === 413) return API_ERROR_MESSAGES["payload too large"][locale];
501 if (err.status >= 500) return locale === "tr" ? "Sunucuda bir sorun oluştu. Lütfen tekrar dene." : "Server error. Please try again.";
502 return formatApiErrorMessage(err.message, locale);
503 }
504 if (err instanceof TypeError) {
505 return formatRuntimeErrorMessage(err.message, locale) ??
506 (locale === "tr"
507 ? "Sayfa yüklenirken bir sorun oluştu. Sayfayı yeniden yükleyip tekrar dene."
508 : "Something went wrong while loading the page. Reload the page and try again.");
509 }
510 if (err instanceof Error) return formatApiErrorMessage(err.message, locale);
511 return locale === "tr" ? "Bir şeyler ters gitti." : "Something went wrong.";
512}