forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBc35a83aBurak Boduroğlu4 months ago440 commits

client.ts532 lines, 19.9 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
352const pendingGets = new Map<string, Promise<unknown>>();
353
354async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
355 const headers: Record<string, string> = {};
356 let body: string | undefined;
357
358 if (options.body !== undefined) {
359 headers["Content-Type"] = "application/json";
360 body = JSON.stringify(options.body);
361 }
362
363 // JSON calls only — uploads (formClient) and downloads (blobClient) stay
364 // untimed. Without this a dead connection leaves callers (exam-room REST
365 // autosave) stuck on "saving…" until the browser gives up.
366 const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
367 // Caller-initiated aborts keep their original AbortError so cancellation
368 // handling upstream is untouched; only our own deadline becomes an ApiError.
369 const asDeadlineError = (err: unknown) =>
370 timeout.aborted && !options.signal?.aborted ? new ApiError(408, "request timed out") : err;
371
372 let res: Response;
373 try {
374 res = await fetch(`${API_PREFIX}${path}`, {
375 method: options.method ?? "GET",
376 headers,
377 body,
378 credentials: "same-origin",
379 signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout,
380 cache: options.cache,
381 });
382 } catch (err) {
383 throw asDeadlineError(err);
384 }
385
386 if (res.status === 204) {
387 return undefined as T;
388 }
389
390 // The deadline aborts the body stream too, so headers can arrive in time and
391 // res.text() still blow up mid-download on a multi-MB response.
392 let text: string;
393 try {
394 text = await res.text();
395 } catch (err) {
396 throw asDeadlineError(err);
397 }
398
399 let data: unknown = null;
400 if (text) {
401 try {
402 data = JSON.parse(text);
403 } catch {
404 data = { error: text };
405 }
406 }
407
408 if (!res.ok) {
409 const message = errorMessageFromPayload(data, res.statusText || "Request failed");
410
411 let retryAfter: number | null = null;
412 if (res.status === 429 || res.status === 503) {
413 const raw = res.headers.get("Retry-After");
414 if (raw) {
415 const n = Number(raw);
416 retryAfter = Number.isFinite(n) ? n : null;
417 }
418 }
419
420 throw new ApiError(res.status, message, retryAfter);
421 }
422
423 return data as T;
424}
425
426/**
427 * Coalesce only overlapping, non-cancellable GETs. This is deliberately not a
428 * cache: once settled the entry disappears, so every later resource refetch
429 * still reaches the backend and mutation consistency stays unchanged.
430 */
431export function client<T>(path: string, options: RequestOptions = {}): Promise<T> {
432 const method = options.method ?? "GET";
433 if (method !== "GET" || options.body !== undefined || options.signal || options.cache === "no-store") {
434 return request<T>(path, options);
435 }
436 const key = `${path}\u0000${options.cache ?? "default"}`;
437 const pending = pendingGets.get(key);
438 if (pending) return pending as Promise<T>;
439 const next = request<T>(path, options).finally(() => pendingGets.delete(key));
440 pendingGets.set(key, next);
441 return next;
442}
443
444export async function formClient<T>(path: string, body: FormData, signal?: AbortSignal): Promise<T> {
445 const res = await fetch(`${API_PREFIX}${path}`, {
446 method: "POST",
447 body,
448 credentials: "same-origin",
449 signal,
450 });
451
452 const text = await res.text();
453 let data: unknown = null;
454 if (text) {
455 try {
456 data = JSON.parse(text);
457 } catch {
458 data = { error: text };
459 }
460 }
461
462 if (!res.ok) {
463 const message = errorMessageFromPayload(data, res.statusText || "Request failed");
464 throw new ApiError(res.status, message);
465 }
466
467 return data as T;
468}
469
470export async function blobClient(path: string, signal?: AbortSignal): Promise<Blob> {
471 const res = await fetch(`${API_PREFIX}${path}`, {
472 credentials: "same-origin",
473 signal,
474 });
475
476 if (!res.ok) {
477 const text = await res.text();
478 let message = res.statusText || "Request failed";
479 if (text) {
480 try {
481 message = errorMessageFromPayload(JSON.parse(text), message);
482 } catch {
483 message = text;
484 }
485 }
486 throw new ApiError(res.status, message);
487 }
488
489 return res.blob();
490}
491
492export function formatApiErrorMessage(message: string, locale: Locale = currentLocale()): string {
493 const normalized = normalizeApiMessage(message);
494 const known = API_ERROR_MESSAGES[normalized]?.[locale];
495 if (known) return known;
496 const runtime = formatRuntimeErrorMessage(message, locale);
497 if (runtime) return runtime;
498 const validation = formatValidationMessage(message, locale);
499 if (validation) return validation;
500 // Unmapped backend text is raw English/technical — never surface it to the
501 // user. Fall back to a clean localized line; add a mapping in
502 // API_ERROR_MESSAGES when a specific message deserves its own wording.
503 return locale === "tr"
504 ? "İşlem tamamlanamadı. Lütfen bilgileri kontrol edip tekrar dene."
505 : "Something went wrong. Please check your input and try again.";
506}
507
508export function formatApiError(err: unknown, locale: Locale = currentLocale()): string {
509 if (err instanceof ApiError) {
510 if ((err.status === 429 || err.status === 503) && err.retryAfter != null) {
511 return locale === "tr" ? `${err.retryAfter} sn sonra tekrar dene.` : `Try again in ${err.retryAfter}s.`;
512 }
513 // The specific backend message wins over the per-status generic one —
514 // otherwise every 401/403/404/413/5xx entry in the table is dead code.
515 const known = API_ERROR_MESSAGES[normalizeApiMessage(err.message)]?.[locale];
516 if (known) return known;
517 if (err.status === 401) return API_ERROR_MESSAGES.unauthorized[locale];
518 if (err.status === 403) return API_ERROR_MESSAGES.forbidden[locale];
519 if (err.status === 404) return API_ERROR_MESSAGES["not found"][locale];
520 if (err.status === 413) return API_ERROR_MESSAGES["payload too large"][locale];
521 if (err.status >= 500) return locale === "tr" ? "Sunucuda bir sorun oluştu. Lütfen tekrar dene." : "Server error. Please try again.";
522 return formatApiErrorMessage(err.message, locale);
523 }
524 if (err instanceof TypeError) {
525 return formatRuntimeErrorMessage(err.message, locale) ??
526 (locale === "tr"
527 ? "Sayfa yüklenirken bir sorun oluştu. Sayfayı yeniden yükleyip tekrar dene."
528 : "Something went wrong while loading the page. Reload the page and try again.");
529 }
530 if (err instanceof Error) return formatApiErrorMessage(err.message, locale);
531 return locale === "tr" ? "Bir şeyler ters gitti." : "Something went wrong.";
532}