-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
437 lines (361 loc) · 10.8 KB
/
Copy pathapi.js
File metadata and controls
437 lines (361 loc) · 10.8 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
// DevHub API Client
// Include this file in all your HTML pages
const API_BASE_URL = ' https://devhub-rshq.onrender.com/api';
// ==================== HELPER FUNCTIONS ====================
// Get token from localStorage
const getToken = () => localStorage.getItem('devhub_token');
// Set token to localStorage
const setToken = (token) => localStorage.setItem('devhub_token', token);
// Remove token from localStorage
const removeToken = () => localStorage.removeItem('devhub_token');
// Get current user from localStorage
const getCurrentUser = () => {
const user = localStorage.getItem('devhub_user');
return user ? JSON.parse(user) : null;
};
// Set current user to localStorage
const setCurrentUser = (user) => {
localStorage.setItem('devhub_user', JSON.stringify(user));
};
// Remove current user from localStorage
const removeCurrentUser = () => {
localStorage.removeItem('devhub_user');
};
// Make API request with optional authentication
const apiRequest = async (endpoint, options = {}) => {
const token = getToken();
const config = {
headers: {
'Content-Type': 'application/json',
...(token && { 'Authorization': `Bearer ${token}` }),
...options.headers,
},
...options,
};
try {
const response = await fetch(`${API_BASE_URL}${endpoint}`, config);
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || 'Request failed');
}
return data;
} catch (error) {
console.error('API Error:', error);
throw error;
}
};
// ==================== AUTHENTICATION API ====================
const AuthAPI = {
// Register new user
register: async (userData) => {
const data = await apiRequest('/auth/register', {
method: 'POST',
body: JSON.stringify(userData),
});
if (data.token) {
setToken(data.token);
setCurrentUser(data.user);
}
return data;
},
// Login user
login: async (email, password) => {
const data = await apiRequest('/auth/login', {
method: 'POST',
body: JSON.stringify({ email, password }),
});
if (data.token) {
setToken(data.token);
setCurrentUser(data.user);
}
return data;
},
// Get current user
getCurrentUser: async () => {
return await apiRequest('/auth/me');
},
// Logout user
logout: () => {
removeToken();
removeCurrentUser();
window.location.href = 'index.html';
},
// Check if user is logged in
isAuthenticated: () => {
return !!getToken();
},
// Get user type (Developer or Client)
getUserType: () => {
const user = getCurrentUser();
return user ? user.userType : null;
},
};
// ==================== DEVELOPER API ====================
const DeveloperAPI = {
// Get all developers with filters
getAll: async (filters = {}) => {
const params = new URLSearchParams(filters).toString();
return await apiRequest(`/developers${params ? `?${params}` : ''}`);
},
// Get single developer by ID
getById: async (id) => {
return await apiRequest(`/developers/${id}`);
},
// Update developer profile
update: async (id, data) => {
return await apiRequest(`/developers/${id}`, {
method: 'PUT',
body: JSON.stringify(data),
});
},
// Delete developer profile
delete: async (id) => {
return await apiRequest(`/developers/${id}`, {
method: 'DELETE',
});
},
// Search developers
search: async (query) => {
return await apiRequest(`/developers?search=${encodeURIComponent(query)}`);
},
// Filter by skill
filterBySkill: async (skill) => {
return await apiRequest(`/developers?skill=${encodeURIComponent(skill)}`);
},
// Filter by location
filterByLocation: async (location) => {
return await apiRequest(`/developers?location=${encodeURIComponent(location)}`);
},
// Filter by rating
filterByRating: async (minRating) => {
return await apiRequest(`/developers?rating=${minRating}`);
},
};
// ==================== PROJECT API ====================
const ProjectAPI = {
// Get all projects
getAll: async (filters = {}) => {
const params = new URLSearchParams(filters).toString();
return await apiRequest(`/projects${params ? `?${params}` : ''}`);
},
// Get single project
getById: async (id) => {
return await apiRequest(`/projects/${id}`);
},
// Create new project
create: async (projectData) => {
return await apiRequest('/projects', {
method: 'POST',
body: JSON.stringify(projectData),
});
},
// Update project
update: async (id, data) => {
return await apiRequest(`/projects/${id}`, {
method: 'PUT',
body: JSON.stringify(data),
});
},
// Delete project
delete: async (id) => {
return await apiRequest(`/projects/${id}`, {
method: 'DELETE',
});
},
// Get projects by status
getByStatus: async (status) => {
return await apiRequest(`/projects?status=${status}`);
},
// Get client's projects
getClientProjects: async (clientId) => {
return await apiRequest(`/projects?clientId=${clientId}`);
},
// Get developer's projects
getDeveloperProjects: async (developerId) => {
return await apiRequest(`/projects?developerId=${developerId}`);
},
};
// ==================== REVIEW API ====================
const ReviewAPI = {
// Get developer reviews
getDeveloperReviews: async (developerId) => {
return await apiRequest(`/reviews/developer/${developerId}`);
},
// Add review
add: async (reviewData) => {
return await apiRequest('/reviews', {
method: 'POST',
body: JSON.stringify(reviewData),
});
},
// Update review
update: async (id, data) => {
return await apiRequest(`/reviews/${id}`, {
method: 'PUT',
body: JSON.stringify(data),
});
},
// Delete review
delete: async (id) => {
return await apiRequest(`/reviews/${id}`, {
method: 'DELETE',
});
},
};
// ==================== MESSAGE API ====================
const MessageAPI = {
// Get all messages
getAll: async (filters = {}) => {
const params = new URLSearchParams(filters).toString();
return await apiRequest(`/messages${params ? `?${params}` : ''}`);
},
// Get conversations
getConversations: async () => {
return await apiRequest('/messages/conversations');
},
// Send message
send: async (receiverId, message) => {
return await apiRequest('/messages', {
method: 'POST',
body: JSON.stringify({ receiverId, message }),
});
},
// Mark message as read
markAsRead: async (id) => {
return await apiRequest(`/messages/${id}/read`, {
method: 'PATCH',
});
},
// Mark all messages from sender as read
markAllAsRead: async (senderId) => {
return await apiRequest(`/messages/read-all/${senderId}`, {
method: 'PATCH',
});
},
// Delete message
delete: async (id) => {
return await apiRequest(`/messages/${id}`, {
method: 'DELETE',
});
},
// Get conversation with specific user
getConversation: async (userId) => {
return await apiRequest(`/messages?conversationWith=${userId}`);
},
};
// ==================== STATS API ====================
const StatsAPI = {
// Get client stats
getClientStats: async (clientId) => {
return await apiRequest(`/stats/client/${clientId}`);
},
// Get developer stats
getDeveloperStats: async (developerId) => {
return await apiRequest(`/stats/developer/${developerId}`);
},
// Get platform stats
getPlatformStats: async () => {
return await apiRequest('/stats/platform');
},
};
// ==================== UTILITY FUNCTIONS ====================
// Check authentication on page load
const checkAuth = () => {
if (!AuthAPI.isAuthenticated()) {
// Redirect to login if not authenticated (except on public pages)
const publicPages = ['index.html', 'login.html', 'register.html', ''];
const currentPage = window.location.pathname.split('/').pop();
if (!publicPages.includes(currentPage)) {
window.location.href = 'index.html';
}
}
};
// Redirect based on user type
const redirectToDashboard = () => {
const userType = AuthAPI.getUserType();
if (userType === 'Developer') {
window.location.href = 'developer-dashboard.html';
} else if (userType === 'Client') {
window.location.href = 'client-dashboard.html';
}
};
// Format date
const formatDate = (dateString) => {
const date = new Date(dateString);
return date.toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric'
});
};
// Format time ago
const timeAgo = (dateString) => {
const date = new Date(dateString);
const now = new Date();
const seconds = Math.floor((now - date) / 1000);
if (seconds < 60) return `${seconds}s ago`;
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
if (seconds < 604800) return `${Math.floor(seconds / 86400)}d ago`;
return formatDate(dateString);
};
// Show loading spinner
const showLoading = (elementId) => {
const element = document.getElementById(elementId);
if (element) {
element.innerHTML = '<div class="spinner">Loading...</div>';
}
};
// Hide loading spinner
const hideLoading = (elementId) => {
const element = document.getElementById(elementId);
if (element) {
element.innerHTML = '';
}
};
// Show error message
const showError = (message, elementId = 'error-message') => {
const element = document.getElementById(elementId);
if (element) {
element.innerHTML = `<div class="error-alert">${message}</div>`;
setTimeout(() => {
element.innerHTML = '';
}, 5000);
} else {
console.error('Error:', message);
}
};
// Show success message
const showSuccess = (message, elementId = 'success-message') => {
const element = document.getElementById(elementId);
if (element) {
element.innerHTML = `<div class="success-alert">${message}</div>`;
setTimeout(() => {
element.innerHTML = '';
}, 5000);
} else {
console.log('Success:', message);
}
};
// ==================== EXPORT FOR USE ====================
// Make APIs available globally
window.DevHubAPI = {
Auth: AuthAPI,
Developer: DeveloperAPI,
Project: ProjectAPI,
Review: ReviewAPI,
Message: MessageAPI,
Stats: StatsAPI,
// Utility functions
checkAuth,
redirectToDashboard,
formatDate,
timeAgo,
showLoading,
hideLoading,
showError,
showSuccess,
getCurrentUser,
getToken,
};
console.log('✅ DevHub API Client loaded successfully!');