-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathoriginal_api.txt
More file actions
2013 lines (1744 loc) · 59.5 KB
/
Copy pathoriginal_api.txt
File metadata and controls
2013 lines (1744 loc) · 59.5 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { API_CONFIG, DEBUG_CONFIG, ENV_UTILS } from './config'
// === AUTHENTICATION & CORE TYPES ===
export interface LoginRequest {
username: string
password: string
}
export interface LoginResponse {
token: string
user_id: number
username: string
first_name: string
last_name: string
email: string
}
export interface ErrorResponse {
message: string
}
export interface ForgotPasswordRequest {
email: string
}
export interface ResetPasswordRequest {
token: string
password: string
confirmPassword: string
}
export interface UserPermissionsSchema {
user_info: Record<string, any>
permissions: Record<string, any>
display_properties: Record<string, any>
role_info: Record<string, any>
}
export interface TanevConfigStatusSchema {
config_necessary: boolean
system_admin_setup_required: boolean
current_tanev?: Record<string, any>
missing_components: string[]
setup_steps: Record<string, any>[]
}
// === PARTNERS ===
export interface PartnerSchema {
id: number
name: string
address: string
institution?: string
imageURL?: string
}
export interface PartnerCreateSchema {
name: string
address?: string
institution?: string
imageURL?: string
}
export interface PartnerUpdateSchema {
name?: string
address?: string
institution?: string
imageURL?: string
}
// === RADIO ===
export interface RadioStabSchema {
id: number
name: string
team_code: string
description?: string
member_count: number
}
export interface RadioStabCreateSchema {
name: string
team_code: string
description?: string
}
export interface RadioSessionSchema {
id: number
radio_stab: RadioStabSchema
date: string
time_from: string
time_to: string
description?: string
participant_count: number
}
export interface RadioSessionCreateSchema {
radio_stab_id: number
date: string
time_from: string
time_to: string
description?: string
participant_ids: number[]
}
// === USERS ===
export interface UserBasicSchema {
id: number
username: string
first_name: string
last_name: string
full_name: string
}
export interface UserProfileSchema {
id: number
username: string
first_name: string
last_name: string
email: string
telefonszam?: string
medias: boolean
admin_type: string
stab_name?: string
radio_stab_name?: string
osztaly_name?: string
is_second_year_radio: boolean
}
export interface UserDetailSchema {
id: number
username: string
first_name: string
last_name: string
email: string
full_name: string
is_active: boolean
admin_type: string
special_role: string
telefonszam?: string
osztaly?: Record<string, any>
stab?: Record<string, any>
radio_stab?: Record<string, any>
medias: boolean
password_set: boolean
first_login_token_sent: boolean
date_joined: string
last_login?: string
}
export interface UserCreateSchema {
username: string
first_name: string
last_name: string
email: string
admin_type?: string
special_role?: string
telefonszam?: string
osztaly_id?: number
stab_id?: number
radio_stab_id?: number
medias?: boolean
}
export interface UserUpdateSchema {
username?: string
first_name?: string
last_name?: string
email?: string
admin_type?: string
special_role?: string
telefonszam?: string
osztaly_id?: number
stab_id?: number
radio_stab_id?: number
medias?: boolean
is_active?: boolean
}
// === ACADEMIC ===
export interface TanevSchema {
id: number
start_date: string
end_date: string
start_year: number
end_year: number
display_name: string
is_active: boolean
osztaly_count: number
}
export interface TanevCreateSchema {
start_date: string
end_date: string
}
export interface OsztalySchema {
id: number
start_year: number
szekcio: string
display_name: string
current_display_name?: string
tanev?: TanevSchema
student_count: number
}
export interface OsztalyCreateSchema {
start_year: number
szekcio: string
tanev_id?: number
}
export interface OsztalyUpdateSchema {
start_year?: number
szekcio?: string
tanev_id?: number
}
// === EQUIPMENT ===
export interface EquipmentTipusSchema {
id: number
name: string
emoji?: string
equipment_count: number
}
export interface EquipmentTipusCreateSchema {
name: string
emoji?: string
}
export interface EquipmentSchema {
id: number
nickname: string
brand?: string
model?: string
serial_number?: string
equipment_type?: EquipmentTipusSchema
functional: boolean
notes?: string
display_name: string
}
export interface EquipmentCreateSchema {
nickname: string
brand?: string
model?: string
serial_number?: string
equipment_type_id?: number
functional?: boolean
notes?: string
}
export interface EquipmentUpdateSchema {
nickname?: string
brand?: string
model?: string
serial_number?: string
equipment_type_id?: number
functional?: boolean
notes?: string
}
export interface EquipmentAvailabilitySchema {
equipment_id: number
available: boolean
conflicts: Record<string, any>[]
}
export interface EquipmentScheduleSchema {
equipment_id: number
equipment_name: string
schedule: {
date: string
time_from: string
time_to: string
forgatas_name: string
forgatas_id: number
forgatas_type: string
location: string
available: boolean
}[]
}
export interface EquipmentUsageSchema {
equipment_id: number
equipment_name: string
total_bookings: number
upcoming_bookings: number
usage_hours: number
most_recent_use: string
next_booking?: {
forgatas_id: number
forgatas_name: string
date: string
time_from: string
time_to: string
location: string
}
}
export interface EquipmentOverviewSchema {
equipment_id: number
equipment_name: string
equipment_type: string
functional: boolean
available_periods: boolean
bookings: {
forgatas_id: number
forgatas_name: string
time_from: string
time_to: string
type: string
location: string
}[]
booking_count: number
}
// === PRODUCTION ===
export interface ContactPersonSchema {
id: number
name: string
email?: string
phone?: string
}
export interface ContactPersonCreateSchema {
name: string
email?: string
phone?: string
}
export interface ForgatSchema {
id: number
name: string
description: string
date: string
time_from: string
time_to: string
location?: Record<string, any>
contact_person?: ContactPersonSchema
notes?: string
type: string
type_display: string
related_kacsa?: Record<string, any>
equipment_ids: number[]
equipment_count: number
tanev?: Record<string, any>
}
export interface ForgatCreateSchema {
name: string
description: string
date: string
time_from: string
time_to: string
location_id?: number
contact_person_id?: number
notes?: string
type: string
related_kacsa_id?: number
equipment_ids?: number[]
}
export interface ForgatUpdateSchema {
name?: string
description?: string
date?: string
time_from?: string
time_to?: string
location_id?: number
contact_person_id?: number
notes?: string
type?: string
related_kacsa_id?: number
equipment_ids?: number[]
}
export interface ForgatoTipusSchema {
value: string
label: string
}
// === COMMUNICATIONS ===
export interface AnnouncementSchema {
id: number
title: string
body: string
author?: UserBasicSchema
created_at: string
updated_at: string
recipient_count: number
is_targeted: boolean
}
export interface AnnouncementDetailSchema extends AnnouncementSchema {
recipients: UserBasicSchema[]
}
export interface AnnouncementCreateSchema {
title: string
body: string
recipient_ids?: number[]
}
export interface AnnouncementUpdateSchema {
title?: string
body?: string
recipient_ids?: number[]
}
// === ORGANIZATION ===
export interface StabSchema {
id: number
name: string
member_count: number
}
export interface StabCreateSchema {
name: string
}
export interface SzerepkorSchema {
id: number
name: string
ev?: number
year_display?: string
}
export interface SzerepkorCreateSchema {
name: string
ev?: number
}
export interface SzerepkorRelacioSchema {
id: number
user: UserBasicSchema
szerepkor: SzerepkorSchema
}
export interface SzerepkorRelacioCreateSchema {
user_id: number
szerepkor_id: number
}
export interface BeosztasSchema {
id: number
forgatas: ForgatSchema
szerepkor_relaciok: SzerepkorRelacioSchema[]
kesz: boolean
author?: UserBasicSchema
created_at: string
student_count: number
roles_summary: { role: string, count: number }[]
}
export interface BeosztasDetailSchema extends BeosztasSchema {
student_role_assignments: Array<{
id: number
user: UserProfileSchema
szerepkor: SzerepkorSchema
}>
created_by: UserProfileSchema | null
created_at: string
updated_at: string
}
export interface AbsenceFromAssignmentSchema {
id: number
student: UserBasicSchema
date: string
time_from: string
time_to: string
excused: boolean
unexcused: boolean
affected_classes: string[]
assignment_role?: {
role: string
}
reason: string
created_at: string
created_by?: UserBasicSchema
}
export interface BeosztasCreateSchema {
kesz?: boolean
tanev_id?: number
szerepkor_relacio_ids?: number[]
}
// === LEGACY BEOSZTAS TYPES ===
export interface LegacyBeosztasItemSchema {
id: number
user_id: number
role: string
}
export interface LegacyForgatBeosztasSchema {
id: number
name: string
description: string
date: string | null
time_from: string | null
time_to: string | null
location: {
id: number
name: string
address: string
} | null
contact_person: {
id: number
name: string
email: string
phone: string
} | null
notes: string | null
type: string
type_display: string
related_kacsa: {
id: number
name: string
date: string
} | null
equipment_ids: number[]
equipment_count: number
beosztas: LegacyBeosztasItemSchema[]
tanev: {
id: number
display_name: string
is_active: boolean
} | null
}
export interface LegacyBeosztasCreateSchema {
beosztas: number
forgatas: number
user: number
role: string
}
// === ABSENCE ===
export interface TavolletSchema {
id: number
user: UserBasicSchema
start_date: string
end_date: string
reason?: string
denied: boolean
approved: boolean
duration_days: number
status: string
}
export interface TavolletCreateSchema {
user_id?: number
start_date: string
end_date: string
reason?: string
}
export interface TavolletUpdateSchema {
start_date?: string
end_date?: string
reason?: string
denied?: boolean
approved?: boolean
}
// === CONFIGURATION ===
export interface ConfigSchema {
id: number
active: boolean
allow_emails: boolean
status: string
}
export interface ConfigUpdateSchema {
active?: boolean
allow_emails?: boolean
}
// === USER MANAGEMENT ===
export interface FirstLoginTokenResponse {
user_id: number
username: string
full_name: string
token_url: string
token: string
expires_at: string
}
export interface BulkEmailResponse {
total_users: number
emails_sent: number
failed_emails: string[]
tokens_generated: number
}
export interface BulkStudentCreateSchema {
osztaly_id: number
students: Record<string, any>[]
send_emails?: boolean
}
// === FILMING/FORGATAS SCHEMAS ===
export interface ContactPersonSchema {
id: number
name: string
email?: string
phone?: string
organization?: string
}
export interface ForgatoTipusSchema {
value: string
label: string
description?: string
}
export interface ForgatCreateSchema {
name: string
description: string
date: string
time_from: string
time_to: string
location_id?: number
contact_person_id?: number
riporter_id?: number
notes?: string
type: string
related_kacsa_id?: number
equipment_ids?: number[]
}
// === STUDENT/REPORTER SCHEMAS ===
export interface StudentSchema {
id: number
username: string
first_name: string
last_name: string
full_name: string
email: string
osztaly?: {
id: number
display_name: string
section: string
start_year: number
}
can_be_reporter: boolean
is_media_student: boolean
}
export interface ReporterSchema {
id: number
username: string
full_name: string
osztaly_display: string
grade_level: number
is_experienced: boolean
}
// === KACSA SESSION SCHEMAS ===
export interface KacsaAvailableSchema {
id: number
name: string
date: string
time_from: string
time_to: string
can_link: boolean
already_linked: boolean
}
// === SCHOOL YEAR SCHEMAS ===
export interface SchoolYearForDateSchema {
id: number
display_name: string
is_active: boolean
date_in_range: boolean
}
// API Client class
class ApiClient {
private baseUrl: string
private token: string | null = null
constructor(baseUrl: string) {
this.baseUrl = baseUrl
// Initialize token as null, will be set when getStoredToken is called
this.token = null
// Only get stored token in browser environment
if (typeof window !== 'undefined') {
this.token = this.getStoredToken()
}
}
private getStoredToken(): string | null {
if (typeof window !== 'undefined') {
// Try localStorage first
const localToken = localStorage.getItem('jwt_token')
if (localToken && localToken.trim() !== '' && localToken !== 'null') {
return localToken.trim()
}
// Fallback to cookies
const cookieToken = document.cookie
.split(';')
.find(cookie => cookie.trim().startsWith('jwt_token='))
?.split('=')[1]
if (cookieToken && cookieToken.trim() !== '' && cookieToken !== 'null') {
return decodeURIComponent(cookieToken.trim())
}
}
return null
}
setToken(token: string | null) {
this.token = token
if (typeof window !== 'undefined') {
if (token && token.trim() !== '') {
const cleanToken = token.trim()
localStorage.setItem('jwt_token', cleanToken)
// Also set as httpOnly cookie for middleware - encode properly
document.cookie = `jwt_token=${encodeURIComponent(cleanToken)}; path=/; max-age=${7 * 24 * 60 * 60}; secure; samesite=strict`
} else {
localStorage.removeItem('jwt_token')
// Remove cookie
document.cookie = 'jwt_token=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT;'
}
}
}
private async request<T>(
endpoint: string,
options: RequestInit = {},
timeout: number = 30000 // 30 seconds default timeout
): Promise<T> {
const url = `${this.baseUrl}${endpoint}`
const headers: Record<string, string> = {
'Content-Type': 'application/json',
...(options.headers as Record<string, string>),
}
if (this.token && this.token.trim() !== '') {
const cleanToken = this.token.trim()
// Ensure we don't double-add 'Bearer' prefix
if (cleanToken.startsWith('Bearer ')) {
headers.Authorization = cleanToken
} else {
headers.Authorization = `Bearer ${cleanToken}`
}
}
// Log API calls in development/staging
if (DEBUG_CONFIG.LOG_API_CALLS) {
console.log(`🔗 API Request [${ENV_UTILS.getCurrentEnvironment()}]:`, {
method: options.method || 'GET',
url,
baseUrl: this.baseUrl,
hasAuthHeader: !!headers.Authorization,
authHeaderPreview: headers.Authorization ? `${headers.Authorization.substring(0, 20)}...` : 'none',
headers: DEBUG_CONFIG.ENABLED ? { ...headers, Authorization: headers.Authorization ? '[PRESENT]' : '[MISSING]' } : '[hidden]',
body: options.body ? JSON.parse(options.body as string) : undefined,
timeout
})
}
// Create abort controller for timeout
const controller = new AbortController()
const timeoutId = setTimeout(() => controller.abort(), timeout)
try {
const response = await fetch(url, {
...options,
headers,
mode: 'cors', // Explicitly set CORS mode
credentials: 'omit', // Don't send credentials to avoid CORS preflight issues
signal: controller.signal,
})
clearTimeout(timeoutId)
// Log response in development
if (DEBUG_CONFIG.LOG_API_CALLS) {
console.log(`📡 API Response [${response.status}]:`, {
url,
status: response.status,
statusText: response.statusText,
ok: response.ok
})
}
if (!response.ok) {
const errorData = await response.json().catch(() => ({
message: `HTTP ${response.status}: ${response.statusText}`
}))
// Enhanced error logging
if (DEBUG_CONFIG.ENABLED) {
console.error(`❌ API Error [${ENV_UTILS.getCurrentEnvironment()}]:`, {
url,
status: response.status,
statusText: response.statusText,
errorData,
headers: DEBUG_CONFIG.DETAILED_ERRORS ? headers : '[hidden]'
})
}
// Handle specific error cases
if (response.status === 401) {
// First, try to refresh token from storage in case it was updated elsewhere
const refreshedToken = this.refreshTokenFromStorage()
if (DEBUG_CONFIG.ENABLED) {
console.warn('🔄 401 Error - attempting token refresh:', {
hadToken: !!this.token,
refreshedToken: !!refreshedToken,
tokenChanged: this.token !== refreshedToken
})
}
// If token changed, retry the request once
if (refreshedToken && refreshedToken !== this.token) {
console.log('🔄 Retrying request with refreshed token')
headers.Authorization = refreshedToken.startsWith('Bearer ') ? refreshedToken : `Bearer ${refreshedToken}`
const retryResponse = await fetch(url, {
...options,
headers,
mode: 'cors',
credentials: 'omit',
})
if (retryResponse.ok) {
const data = await retryResponse.json()
if (DEBUG_CONFIG.ENABLED && DEBUG_CONFIG.LOG_LEVEL === 'debug') {
console.log(`✅ API Retry Success:`, { url, data })
}
return data
}
}
// Check if this is a public endpoint that shouldn't require auth
const publicEndpoints = [
'/api/hello',
'/api/test-auth',
'/api/partners',
'/api/filming-sessions/types',
'/api/first-login/verify-token',
'/api/first-login/set-password',
'/api/config/status'
]
const isPublicEndpoint = publicEndpoints.some(publicPath =>
endpoint.startsWith(publicPath)
)
if (isPublicEndpoint) {
// For public endpoints, don't clear token and use specific error message
throw new Error(errorData.message || 'Hitelesítési hiba történt.')
} else {
// For protected endpoints, clear invalid token
this.setToken(null)
throw new Error('A munkamenet lejárt. Kérjük, jelentkezzen be újra.')
}
} else if (response.status === 403) {
throw new Error('Nincs jogosultsága ehhez a művelethez.')
} else if (response.status === 404) {
throw new Error('A kért erőforrás nem található.')
} else if (response.status >= 500) {
throw new Error('Szerverhiba történt. Kérjük, próbálja újra később.')
}
throw new Error(errorData.message || 'API request failed')
}
const data = await response.json()
// Log successful response data in debug mode
if (DEBUG_CONFIG.ENABLED && DEBUG_CONFIG.LOG_LEVEL === 'debug') {
console.log(`✅ API Success:`, { url, data, isEmpty: Array.isArray(data) && data.length === 0 })
}
return data
} catch (error) {
clearTimeout(timeoutId)
// Enhanced error handling with environment context
if (DEBUG_CONFIG.ENABLED) {
console.error(`💥 API Request Failed [${ENV_UTILS.getCurrentEnvironment()}]:`, {
url,
error: error instanceof Error ? error.message : String(error),
baseUrl: this.baseUrl,
environment: ENV_UTILS.getCurrentEnvironment(),
isAbortError: error instanceof Error && error.name === 'AbortError'
})
}
// Check for timeout/abort errors
if (error instanceof Error && error.name === 'AbortError') {
throw new Error(`Kérés időtúllépés: A szerver nem válaszolt ${timeout / 1000} másodperc alatt. Kérjük, próbálja újra.`)
}
// Check for CORS errors specifically and provide helpful message
if (error instanceof TypeError &&
(error.message.includes('Failed to fetch') ||
error.message.includes('NetworkError') ||
error.message.includes('CORS'))) {
const corsMessage = `Hálózati hiba: Nem sikerült csatlakozni a szerverhez (${this.baseUrl}). Ellenőrizze az internetkapcsolatot és próbálja újra.`
console.error('🚫 Network Error Details:', {
frontendOrigin: typeof window !== 'undefined' ? window.location.origin : 'unknown',
backendUrl: this.baseUrl,
error: error.message,
suggestion: 'Check internet connection and server availability.'
})
throw new Error(corsMessage)
}
// Re-throw the error for the calling code
throw error
}
}
// === RETRY WRAPPER METHODS ===
private async withRetry<T>(
operation: () => Promise<T>,
context: string,
maxRetries: number = 3,
timeout?: number
): Promise<T> {
let lastError: Error | null = null
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await operation()
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error))
// Don't retry on certain errors
if (this.shouldNotRetry(lastError)) {
throw lastError
}
// If this was the last attempt, throw the error
if (attempt === maxRetries) {
console.error(`❌ Final retry attempt failed for ${context}:`, lastError.message)
throw lastError
}
const delay = Math.min(1000 * Math.pow(2, attempt), 10000) // Exponential backoff with max 10s
console.warn(`⚠️ Attempt ${attempt + 1} failed for ${context}, retrying in ${delay}ms:`, lastError.message)
await new Promise(resolve => setTimeout(resolve, delay))
}
}
throw lastError || new Error('Maximum retries reached')
}
private shouldNotRetry(error: Error): boolean {
// Don't retry on authentication errors
if (error.message.includes('401') || error.message.includes('Unauthorized') ||
error.message.includes('munkamenet lejárt')) {
return true
}
// Don't retry on permission errors
if (error.message.includes('403') || error.message.includes('Forbidden') ||
error.message.includes('jogosultság')) {
return true
}
// Don't retry on client errors (except timeout)
if (error.message.includes('400') && !error.message.includes('időtúllépés')) {
return true
}
return false
}
// Retry-enabled request wrapper
private async requestWithRetry<T>(
endpoint: string,
options: RequestInit = {},
timeout?: number,
maxRetries?: number
): Promise<T> {
return this.withRetry(
() => this.request<T>(endpoint, options, timeout),
`${options.method || 'GET'} ${endpoint}`,
maxRetries,
timeout
)
}
// === CORE & AUTH METHODS ===
async hello(name?: string): Promise<any> {
const params = name ? `?name=${encodeURIComponent(name)}` : ''
return this.request(`/api/hello${params}`)