-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
114 lines (94 loc) · 3.04 KB
/
Copy pathapi.js
File metadata and controls
114 lines (94 loc) · 3.04 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
class APIService {
constructor() {
const isLocalhost = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
this.baseURL = isLocalhost
? 'http://localhost:5000/api'
: 'https://quickbucks-mtkl.onrender.com/api';
this.token = localStorage.getItem('authToken');
}
async request(endpoint, options = {}) {
const url = `${this.baseURL}${endpoint}`;
const config = {
headers: {
'Content-Type': 'application/json',
...(this.token && { 'Authorization': `Bearer ${this.token}` })
},
...options
};
try {
const response = await fetch(url, config);
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'Request failed');
}
return data;
} catch (error) {
console.error('API Error:', error);
if (error.message.includes('token') || error.message.includes('auth')) {
this.logout();
}
throw error;
}
}
// Auth methods
async login(email, password) {
const data = await this.request('/auth/login', {
method: 'POST',
body: JSON.stringify({ email, password })
});
this.token = data.token;
localStorage.setItem('authToken', data.token);
localStorage.setItem('user', JSON.stringify(data.user));
return data;
}
async register(name, email, password) {
const data = await this.request('/auth/register', {
method: 'POST',
body: JSON.stringify({ name, email, password })
});
this.token = data.token;
localStorage.setItem('authToken', data.token);
localStorage.setItem('user', JSON.stringify(data.user));
return data;
}
logout() {
this.token = null;
localStorage.removeItem('authToken');
localStorage.removeItem('user');
window.location.href = 'login.html';
}
// Task methods
async getTasks() {
return await this.request('/tasks');
}
async createTask(taskData) {
return await this.request('/tasks', {
method: 'POST',
body: JSON.stringify(taskData)
});
}
async completeTask(taskId) {
return await this.request(`/tasks/${taskId}/complete`, {
method: 'PATCH'
});
}
async deleteTask(taskId) {
return await this.request(`/tasks/${taskId}`, {
method: 'DELETE'
});
}
// Analytics methods
async getStats() {
return await this.request('/analytics/stats');
}
async getInsights() {
return await this.request('/analytics/insights');
}
async getPatterns() {
return await this.request('/analytics/patterns');
}
isAuthenticated() {
return !!this.token;
}
}
const api = new APIService();