-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapi.js
More file actions
184 lines (154 loc) · 4.95 KB
/
api.js
File metadata and controls
184 lines (154 loc) · 4.95 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
// API Configuration and Authentication
const API_BASE_URL = 'http://localhost:4000/api';
// Token management
const getToken = () => localStorage.getItem('authToken');
const setToken = (token) => {
localStorage.setItem('authToken', token);
};
const removeToken = () => {
localStorage.removeItem('authToken');
localStorage.removeItem('userId');
localStorage.removeItem('userName');
localStorage.removeItem('userRole');
};
// API request helper
const apiRequest = async (endpoint, options = {}) => {
const token = getToken();
const config = {
headers: {
'Content-Type': 'application/json',
...(token && { 'x-auth-token': token }),
...options.headers,
},
...options,
};
if(options.body instanceof FormData){
delete config.headers['Content-Type']; // Let browser set it for FormData
}
try {
const response = await fetch(`${API_BASE_URL}${endpoint}`, config);
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'API request failed');
}
return data;
} catch (error) {
console.error('API Error:', error);
throw error;
}
};
// Authentication API calls
const authAPI = {
login: async (email, password) => {
const response = await apiRequest('/auth/login', {
method: 'POST',
body: JSON.stringify({ instituteEmailId: email, password }),
});
if (response.token) {
// Save token
setToken(response.token);
// Save user details if backend sends them
if (response.user) {
localStorage.setItem("userId", response.user._id || "");
localStorage.setItem("userName", response.user.name || response.user.instituteEmailId||"");
localStorage.setItem("userRole", response.user.role || "");
}
}
return response;
},
register: async (name, email, password, role) => {
const response = await apiRequest('/auth/register', {
method: 'POST',
body: JSON.stringify({ name, instituteEmailId: email, password, role }),
});
if (response.token) {
setToken(response.token);
}
return response;
},
logout: () => {
removeToken();
window.location.href = '/login.html';
}
};
// Complaint API calls
const complaintAPI = {
submit: async (formData) => {
const token = getToken();
const response = await fetch(`${API_BASE_URL}/complaints/submit`, {
method: 'POST',
headers: {
'x-auth-token': token,
},
body: formData, // FormData for file upload
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'Failed to submit complaint');
}
return data;
},
getMyComplaints: async (page = 1, limit = 10, status = '') => {
const params = new URLSearchParams({ page, limit });
if (status) params.append('status', status);
return await apiRequest(`/complaints/my-complaints?${params}`);
},
getAdminDashboard: async () => {
return await apiRequest('/complaints/admin/dashboard');
},
resolveComplaint: async (complaintId, resolutionNotes = '') => {
return await apiRequest(`/complaints/${complaintId}/resolve`, {
method: 'PATCH',
body: JSON.stringify({ resolutionNotes }),
});
},
deleteComplaint: async (complaintId) => {
return await apiRequest(`/complaints/${complaintId}`, {
method: 'DELETE',
});
}
};
// User API calls
const userAPI = {
getProfile: async () => {
return await apiRequest('/users/profile');
},
updateProfile: async (userData) => {
return await apiRequest('/users/profile', {
method: 'PUT',
body: JSON.stringify(userData),
});
},
getAllUsers: async () => {
return await apiRequest('/users');
}
};
// Utility functions
const isAuthenticated = () => !!getToken();
// Redirect if not authenticated
const redirectIfNotAuthenticated = () => {
if (!isAuthenticated()) {
window.location.href = '/login.html';
return true;
}
return false;
};
const showMessage = (message, type = 'info') => {
const messageDiv = document.createElement('div');
messageDiv.className = `message ${type}`;
messageDiv.textContent = message;
messageDiv.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
padding: 10px 20px;
border-radius: 5px;
color: white;
z-index: 1000;
background-color: ${type === 'error' ? '#dc3545' : type === 'success' ? '#28a745' : '#007bff'};
`;
document.body.appendChild(messageDiv);
setTimeout(() => {
messageDiv.remove();
}, 3000);
};