forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB4e0a329Burak Boduroğlu2 months ago537 commits

client.ts557 lines, 20.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 // Builder surface (web/builder.rs, tenant.rs) — byte-exact.
109 "school slug already taken": {
110 en: "That school code is already taken.",
111 tr: "Bu okul kodu zaten kullanılıyor.",
112 },
113 "that account is not an admin of this school": {
114 en: "That account exists but is not an admin of this school.",
115 tr: "Bu hesap var ama bu okulun yöneticisi değil.",
116 },
117 "school is suspended": {
118 en: "This school is suspended.",
119 tr: "Bu okul askıya alınmış.",
120 },
121 // Booking/decision conflicts from domain/appointment.rs — byte-exact.
122 "the slot is already booked": {
123 en: "Someone else booked this time first.",
124 tr: "Bu saati senden önce başkası aldı.",
125 },
126 "the slot has already started": {
127 en: "This time has already started, so it can no longer be booked.",
128 tr: "Bu saat başladığı için artık randevu alınamaz.",
129 },
130 "you already have an appointment at that time": {
131 en: "You already have an appointment at that time.",
132 tr: "O saatte zaten bir randevun var.",
133 },
134 "the appointment is already settled": {
135 en: "This appointment is already settled.",
136 tr: "Bu randevu zaten sonuçlanmış.",
137 },
138 "the appointment has already started": {
139 en: "This appointment has already started.",
140 tr: "Bu randevu çoktan başladı.",
141 },
142 "that time has already started": {
143 en: "That time has already started. Pick a later one.",
144 tr: "O saat çoktan başladı. Daha ileri bir saat seç.",
145 },
146 "no time has been proposed": {
147 en: "No time has been proposed for this appointment yet.",
148 tr: "Bu randevu için henüz bir saat önerilmedi.",
149 },
150 "the appointment is no longer pending": {
151 en: "This appointment is no longer waiting for an answer.",
152 tr: "Bu randevu artık yanıt bekliyor değil.",
153 },
154 "question: this question did not come from a bank template": {
155 en: "This question was not copied from a bank template, so there is nothing to refresh it from.",
156 tr: "Bu soru bir banka şablonundan kopyalanmadığı için yenilenecek bir kaynağı yok.",
157 },
158 "request timed out": {
159 en: "The server did not respond in time. Check your connection and try again.",
160 tr: "Sunucu zamanında yanıt vermedi. Bağlantını kontrol edip tekrar dene.",
161 },
162 "only the template's owner or an admin can change it": {
163 en: "Only the teacher who created this template (or an admin) can change it.",
164 tr: "Bu şablonu yalnızca onu oluşturan öğretmen (veya bir yönetici) değiştirebilir.",
165 },
166 "only the course creator, an assigned teacher, or a manager/admin can author questions": {
167 en: "Only this course's teachers or a manager can add questions to this exam.",
168 tr: "Bu sınava yalnızca dersin öğretmenleri veya bir müdür soru ekleyebilir.",
169 },
170 "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank": {
171 en: "Only this course's teachers or a manager can save this question to the bank.",
172 tr: "Bu soruyu bankaya yalnızca dersin öğretmenleri veya bir müdür kaydedebilir.",
173 },
174 "cannot change questions after attempts have started": {
175 en: "Students have already started this exam, so its questions can no longer change.",
176 tr: "Öğrenciler bu sınava başladığı için soruları artık değiştirilemez.",
177 },
178 "bank questions still reference this subject — re-tag or delete them first": {
179 en: "Question bank templates still use this subject. Re-tag or delete them first.",
180 tr: "Soru bankasındaki şablonlar hâlâ bu konuyu kullanıyor. Önce onları başka konuya taşı veya sil.",
181 },
182 "the term is archived — past years are read-only": {
183 en: "This term is archived. Past years are read-only.",
184 tr: "Bu dönem arşivli. Geçmiş dönemler salt okunur.",
185 },
186 "this course's term is archived — past years are read-only": {
187 en: "This course's term is archived. Past years are read-only.",
188 tr: "Bu dersin dönemi arşivli. Geçmiş dönemler salt okunur.",
189 },
190 "module disabled": {
191 en: "This feature is not enabled for your school.",
192 tr: "Bu özellik okulunuz için etkin değil.",
193 },
194 "course not found": {
195 en: "Course not found.",
196 tr: "Ders bulunamadı.",
197 },
198 "exam not found": {
199 en: "Exam not found.",
200 tr: "Sınav bulunamadı.",
201 },
202 "not enrolled in this exam's course": {
203 en: "You are not enrolled in this exam's course.",
204 tr: "Bu sınavın dersine kayıtlı değilsin.",
205 },
206 "you are not enrolled in this exam's course": {
207 en: "You are not enrolled in this exam's course.",
208 tr: "Bu sınavın dersine kayıtlı değilsin.",
209 },
210 "exam is not scheduled": {
211 en: "This exam is not scheduled for online sitting.",
212 tr: "Bu sınav çevrim içi oturum için zamanlanmamış.",
213 },
214 "attempt not found": {
215 en: "Start the exam before opening the exam room.",
216 tr: "Sınav odasını açmadan önce sınavı başlat.",
217 },
218 "attempt is closed": {
219 en: "This attempt is closed. Answers are read-only.",
220 tr: "Bu oturum kapalı. Cevaplar salt okunur.",
221 },
222 "exam has not started": {
223 en: "This exam has not started yet.",
224 tr: "Bu sınav henüz başlamadı.",
225 },
226 "exam has ended": {
227 en: "This exam has ended.",
228 tr: "Bu sınav sona erdi.",
229 },
230 "no attempts left": {
231 en: "No attempts left for this exam.",
232 tr: "Bu sınav için deneme hakkı kalmadı.",
233 },
234 "answer is required": {
235 en: "Enter an answer before saving.",
236 tr: "Kaydetmeden önce cevap gir.",
237 },
238 "only students can sit exams": {
239 en: "Only students can take exams.",
240 tr: "Sınava yalnızca öğrenciler girebilir.",
241 },
242 "user_id: only students can be enrolled in a course": {
243 en: "Only students can be enrolled in a course.",
244 tr: "Derse yalnızca öğrenciler kaydedilebilir.",
245 },
246 "user_id: only students can be graded": {
247 en: "Only students can be graded.",
248 tr: "Yalnızca öğrencilere not verilebilir.",
249 },
250 "user_id: only students can be marked present in a lesson": {
251 en: "Only students can be marked on a lesson roll call.",
252 tr: "Ders yoklamasında yalnızca öğrenciler işaretlenebilir.",
253 },
254 "event is full": {
255 en: "This event is full.",
256 tr: "Bu etkinlik dolu.",
257 },
258 "registration is closed": {
259 en: "Registration is closed for this event.",
260 tr: "Bu etkinlik için kayıt kapalı.",
261 },
262 "already registered": {
263 en: "This student is already registered.",
264 tr: "Bu öğrenci zaten kayıtlı.",
265 },
266 "already enrolled": {
267 en: "This student is already enrolled.",
268 tr: "Bu öğrenci zaten kayıtlı.",
269 },
270 "active pomodoro session already exists": {
271 en: "You already have a focus session running.",
272 tr: "Zaten devam eden bir odak oturumun var.",
273 },
274 "no active pomodoro session": {
275 en: "There is no active focus session to finish.",
276 tr: "Bitirilecek aktif odak oturumu yok.",
277 },
278};
279
280const FIELD_LABELS: Record<string, Record<Locale, string>> = {
281 content: { en: "Content", tr: "İçerik" },
282 description: { en: "Description", tr: "Açıklama" },
283 password: { en: "Password", tr: "Şifre" },
284 title: { en: "Title", tr: "Başlık" },
285 username: { en: "Username", tr: "Kullanıcı adı" },
286};
287
288export function currentLocale(): Locale {
289 if (typeof window === "undefined") return "en";
290 try {
291 const saved = window.localStorage.getItem("hezarfen.locale");
292 if (saved === "en" || saved === "tr") return saved;
293 return window.navigator.language.toLowerCase().startsWith("tr") ? "tr" : "en";
294 } catch {
295 return "en";
296 }
297}
298
299function normalizeApiMessage(message: string): string {
300 return message
301 .trim()
302 .replace(/[’‘]/g, "'")
303 .replace(/\s+/g, " ")
304 .replace(/[.!?]+$/, "")
305 .toLowerCase();
306}
307
308function sentenceCase(message: string): string {
309 const trimmed = message.trim();
310 if (!trimmed) return trimmed;
311 return trimmed[0].toLocaleUpperCase("en-US") + trimmed.slice(1);
312}
313
314function formatRuntimeErrorMessage(message: string, locale: Locale): string | null {
315 const normalized = normalizeApiMessage(message);
316 if (/^(failed to fetch|load failed|networkerror|network request failed)/.test(normalized)) {
317 return locale === "tr"
318 ? "Sunucuya ulaşılamadı. Bağlantını kontrol edip tekrar dene."
319 : "Could not reach the server. Check your connection and try again.";
320 }
321 if (
322 /^(typeerror:\s*)?cannot (read|set) propert(y|ies) of (null|undefined)/.test(normalized) ||
323 /^use\w+ must be used within \w+provider/.test(normalized)
324 ) {
325 return locale === "tr"
326 ? "Sayfa yüklenirken bir sorun oluştu. Sayfayı yeniden yükleyip tekrar dene."
327 : "Something went wrong while loading the page. Reload the page and try again.";
328 }
329 return null;
330}
331
332function formatNumber(value: string, locale: Locale): string {
333 return new Intl.NumberFormat(locale === "tr" ? "tr-TR" : "en-US").format(Number(value));
334}
335
336function fieldLabel(field: string, locale: Locale): string {
337 const normalized = field.trim().toLowerCase().replace(/[_.-]+/g, " ");
338 const known = FIELD_LABELS[normalized]?.[locale];
339 if (known) return known;
340 return sentenceCase(normalized);
341}
342
343function formatValidationMessage(message: string, locale: Locale): string | null {
344 const lengthMatch = message.match(/^([\w .-]+) must be at most (\d+) characters \(got (\d+)\)$/i);
345 if (!lengthMatch) return null;
346
347 const label = fieldLabel(lengthMatch[1], locale);
348 const max = formatNumber(lengthMatch[2], locale);
349 const got = formatNumber(lengthMatch[3], locale);
350
351 if (locale === "tr") return `${label} en fazla ${max} karakter olmalı. Şu an ${got} karakter.`;
352 return `${label} must be at most ${max} characters. Currently ${got} characters.`;
353}
354
355function errorMessageFromPayload(data: unknown, fallback: string): string {
356 if (!data || typeof data !== "object") return fallback;
357 const record = data as Record<string, unknown>;
358 if (typeof record.error === "string") return record.error;
359 if (typeof record.message === "string") return record.message;
360 const detail = record.detail;
361 if (typeof detail === "string") return detail;
362 if (Array.isArray(detail)) {
363 return detail
364 .map((item) => {
365 if (!item || typeof item !== "object") return "";
366 const row = item as Record<string, unknown>;
367 const loc = Array.isArray(row.loc) ? row.loc.map(String).join(".") : "";
368 const msg = typeof row.msg === "string" ? row.msg : "";
369 return loc && msg ? `${loc}: ${msg}` : msg;
370 })
371 .filter(Boolean)
372 .join("; ") || fallback;
373 }
374 return fallback;
375}
376
377const pendingGets = new Map<string, Promise<unknown>>();
378
379async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
380 const headers: Record<string, string> = {};
381 let body: string | undefined;
382
383 if (options.body !== undefined) {
384 headers["Content-Type"] = "application/json";
385 body = JSON.stringify(options.body);
386 }
387
388 // JSON calls only — uploads (formClient) and downloads (blobClient) stay
389 // untimed. Without this a dead connection leaves callers (exam-room REST
390 // autosave) stuck on "saving…" until the browser gives up.
391 const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
392 // Caller-initiated aborts keep their original AbortError so cancellation
393 // handling upstream is untouched; only our own deadline becomes an ApiError.
394 const asDeadlineError = (err: unknown) =>
395 timeout.aborted && !options.signal?.aborted ? new ApiError(408, "request timed out") : err;
396
397 let res: Response;
398 try {
399 res = await fetch(`${API_PREFIX}${path}`, {
400 method: options.method ?? "GET",
401 headers,
402 body,
403 credentials: "same-origin",
404 signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout,
405 cache: options.cache,
406 });
407 } catch (err) {
408 throw asDeadlineError(err);
409 }
410
411 if (res.status === 204) {
412 return undefined as T;
413 }
414
415 // The deadline aborts the body stream too, so headers can arrive in time and
416 // res.text() still blow up mid-download on a multi-MB response.
417 let text: string;
418 try {
419 text = await res.text();
420 } catch (err) {
421 throw asDeadlineError(err);
422 }
423
424 let data: unknown = null;
425 if (text) {
426 try {
427 data = JSON.parse(text);
428 } catch {
429 data = { error: text };
430 }
431 }
432
433 if (!res.ok) {
434 const message = errorMessageFromPayload(data, res.statusText || "Request failed");
435
436 let retryAfter: number | null = null;
437 if (res.status === 429 || res.status === 503) {
438 const raw = res.headers.get("Retry-After");
439 if (raw) {
440 const n = Number(raw);
441 retryAfter = Number.isFinite(n) ? n : null;
442 }
443 }
444
445 throw new ApiError(res.status, message, retryAfter);
446 }
447
448 return data as T;
449}
450
451/**
452 * Coalesce only overlapping, non-cancellable GETs. This is deliberately not a
453 * cache: once settled the entry disappears, so every later resource refetch
454 * still reaches the backend and mutation consistency stays unchanged.
455 */
456export function client<T>(path: string, options: RequestOptions = {}): Promise<T> {
457 const method = options.method ?? "GET";
458 if (method !== "GET" || options.body !== undefined || options.signal || options.cache === "no-store") {
459 return request<T>(path, options);
460 }
461 const key = `${path}\u0000${options.cache ?? "default"}`;
462 const pending = pendingGets.get(key);
463 if (pending) return pending as Promise<T>;
464 const next = request<T>(path, options).finally(() => pendingGets.delete(key));
465 pendingGets.set(key, next);
466 return next;
467}
468
469export async function formClient<T>(path: string, body: FormData, signal?: AbortSignal): Promise<T> {
470 const res = await fetch(`${API_PREFIX}${path}`, {
471 method: "POST",
472 body,
473 credentials: "same-origin",
474 signal,
475 });
476
477 const text = await res.text();
478 let data: unknown = null;
479 if (text) {
480 try {
481 data = JSON.parse(text);
482 } catch {
483 data = { error: text };
484 }
485 }
486
487 if (!res.ok) {
488 const message = errorMessageFromPayload(data, res.statusText || "Request failed");
489 throw new ApiError(res.status, message);
490 }
491
492 return data as T;
493}
494
495export async function blobClient(path: string, signal?: AbortSignal): Promise<Blob> {
496 const res = await fetch(`${API_PREFIX}${path}`, {
497 credentials: "same-origin",
498 signal,
499 });
500
501 if (!res.ok) {
502 const text = await res.text();
503 let message = res.statusText || "Request failed";
504 if (text) {
505 try {
506 message = errorMessageFromPayload(JSON.parse(text), message);
507 } catch {
508 message = text;
509 }
510 }
511 throw new ApiError(res.status, message);
512 }
513
514 return res.blob();
515}
516
517export function formatApiErrorMessage(message: string, locale: Locale = currentLocale()): string {
518 const normalized = normalizeApiMessage(message);
519 const known = API_ERROR_MESSAGES[normalized]?.[locale];
520 if (known) return known;
521 const runtime = formatRuntimeErrorMessage(message, locale);
522 if (runtime) return runtime;
523 const validation = formatValidationMessage(message, locale);
524 if (validation) return validation;
525 // Unmapped backend text is raw English/technical — never surface it to the
526 // user. Fall back to a clean localized line; add a mapping in
527 // API_ERROR_MESSAGES when a specific message deserves its own wording.
528 return locale === "tr"
529 ? "İşlem tamamlanamadı. Lütfen bilgileri kontrol edip tekrar dene."
530 : "Something went wrong. Please check your input and try again.";
531}
532
533export function formatApiError(err: unknown, locale: Locale = currentLocale()): string {
534 if (err instanceof ApiError) {
535 if ((err.status === 429 || err.status === 503) && err.retryAfter != null) {
536 return locale === "tr" ? `${err.retryAfter} sn sonra tekrar dene.` : `Try again in ${err.retryAfter}s.`;
537 }
538 // The specific backend message wins over the per-status generic one —
539 // otherwise every 401/403/404/413/5xx entry in the table is dead code.
540 const known = API_ERROR_MESSAGES[normalizeApiMessage(err.message)]?.[locale];
541 if (known) return known;
542 if (err.status === 401) return API_ERROR_MESSAGES.unauthorized[locale];
543 if (err.status === 403) return API_ERROR_MESSAGES.forbidden[locale];
544 if (err.status === 404) return API_ERROR_MESSAGES["not found"][locale];
545 if (err.status === 413) return API_ERROR_MESSAGES["payload too large"][locale];
546 if (err.status >= 500) return locale === "tr" ? "Sunucuda bir sorun oluştu. Lütfen tekrar dene." : "Server error. Please try again.";
547 return formatApiErrorMessage(err.message, locale);
548 }
549 if (err instanceof TypeError) {
550 return formatRuntimeErrorMessage(err.message, locale) ??
551 (locale === "tr"
552 ? "Sayfa yüklenirken bir sorun oluştu. Sayfayı yeniden yükleyip tekrar dene."
553 : "Something went wrong while loading the page. Reload the page and try again.");
554 }
555 if (err instanceof Error) return formatApiErrorMessage(err.message, locale);
556 return locale === "tr" ? "Bir şeyler ters gitti." : "Something went wrong.";
557}