-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapiClient.js
More file actions
129 lines (116 loc) · 4.67 KB
/
Copy pathapiClient.js
File metadata and controls
129 lines (116 loc) · 4.67 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
// * @author EK
const DEBUG_MODE = true;
async function apiCall(url, options = {}) {
try {
const token = localStorage.getItem('jwtToken');
if (DEBUG_MODE) {
console.log('🔍 API Call:', {
url: url,
method: options.method || 'GET',
hasToken: !!token,
tokenStart: token ? token.substring(0, 20) + '...' : 'NONE'
});
}
if (!token && !url.includes('/api/auth/login')) {
console.warn('API Call ohne Token für URL:', url);
}
const response = await fetch(url, {
...options,
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
...options.headers
},
body: options.body ? (typeof options.body === 'string' ? options.body : JSON.stringify(options.body)) : undefined
});
if (DEBUG_MODE) {
console.log('📥 API Response:', {
status: response.status,
statusText: response.statusText,
url: url
});
}
if (response.status === 401) {
console.log('🔒 Token ungültig - Automatische Weiterleitung zur Anmeldung');
if (typeof showError === 'function') {
showError('Sitzung abgelaufen. Sie werden zur Anmeldung weitergeleitet...');
}
setTimeout(() => {
localStorage.clear();
window.location.href = '/';
}, 2000);
return Promise.reject(new Error('Sitzung abgelaufen'));
}
if (response.status === 403) {
console.log('🚫 Zugriff verweigert (403) - Details:', {
url,
method: options.method || 'GET',
userEmail: localStorage.getItem('userEmail'),
userRoles: localStorage.getItem('userRoles')
});
throw new Error(`Zugriff verweigert (403). Möglicherweise fehlen Berechtigungen für: ${options.method || 'GET'} ${url}`);
}
if (!response.ok) {
let errorMessage = `HTTP ${response.status} ${response.statusText}`;
try {
const contentType = response.headers.get('content-type');
if (contentType && contentType.includes('application/json')) {
const errorData = await response.json();
if (errorData.message) {
errorMessage = errorData.message;
} else if (errorData.error) {
errorMessage = errorData.error;
} else if (typeof errorData === 'string') {
errorMessage = errorData;
} else if (errorData.errors && Array.isArray(errorData.errors)) {
errorMessage = errorData.errors.join(', ');
}
} else {
const errorText = await response.text();
if (errorText && errorText.trim()) {
errorMessage = errorText;
}
}
} catch (parseError) {
console.log('⚠️ Konnte Fehlermessage nicht parsen:', parseError);
}
if (DEBUG_MODE) {
console.log('❌ API Error Details:', {
status: response.status,
originalMessage: errorMessage,
url: url
});
}
if (errorMessage.includes('bereits ein Zeiteintrag') || errorMessage.includes('existiert bereits')) {
throw new Error('DUPLICATE_ENTRY|' + errorMessage);
}
throw new Error(errorMessage);
}
const contentType = response.headers.get('content-type');
if (response.status === 204) { // No Content
return {}; // Leeres Objekt zurückgeben
}
if (contentType && contentType.includes('application/json')) {
const data = await response.json();
if (DEBUG_MODE) {
console.log('✅ API Success Data:', data);
}
return data;
} else {
const text = await response.text();
if (DEBUG_MODE) {
console.log('✅ API Success Text:', text);
}
try {
if (text.trim().startsWith('{') && text.trim().endsWith('}')) {
return JSON.parse(text);
}
} catch (e) {
return text;
}
}
} catch (error) {
console.error('🔥 API Call Error:', error);
throw error;
}
}