forked from microsoft/github-copilot-vibe-coding-workshop
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
117 lines (99 loc) · 2.74 KB
/
Copy pathapi.js
File metadata and controls
117 lines (99 loc) · 2.74 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
const API_BASE_URL = 'http://localhost:8000/api';
class ApiService {
async request(endpoint, options = {}) {
const url = `${API_BASE_URL}${endpoint}`;
const config = {
headers: {
'Content-Type': 'application/json',
...options.headers,
},
...options,
};
try {
const response = await fetch(url, config);
if (!response.ok) {
if (response.status === 404) {
throw new Error('Resource not found');
}
if (response.status === 400) {
throw new Error('Bad request - invalid input');
}
if (response.status >= 500) {
throw new Error('Server error - please try again later');
}
throw new Error(`HTTP error! status: ${response.status}`);
}
// Handle 204 No Content responses
if (response.status === 204) {
return null;
}
return await response.json();
} catch (error) {
if (error.name === 'TypeError' && error.message.includes('fetch')) {
throw new Error('Backend server is unavailable. Please check if the server is running.');
}
throw error;
}
}
// Posts API
async getPosts() {
return this.request('/posts');
}
async createPost(postData) {
return this.request('/posts', {
method: 'POST',
body: JSON.stringify(postData),
});
}
async getPost(postId) {
return this.request(`/posts/${postId}`);
}
async updatePost(postId, postData) {
return this.request(`/posts/${postId}`, {
method: 'PATCH',
body: JSON.stringify(postData),
});
}
async deletePost(postId) {
return this.request(`/posts/${postId}`, {
method: 'DELETE',
});
}
// Comments API
async getComments(postId) {
return this.request(`/posts/${postId}/comments`);
}
async createComment(postId, commentData) {
return this.request(`/posts/${postId}/comments`, {
method: 'POST',
body: JSON.stringify(commentData),
});
}
async getComment(postId, commentId) {
return this.request(`/posts/${postId}/comments/${commentId}`);
}
async updateComment(postId, commentId, commentData) {
return this.request(`/posts/${postId}/comments/${commentId}`, {
method: 'PATCH',
body: JSON.stringify(commentData),
});
}
async deleteComment(postId, commentId) {
return this.request(`/posts/${postId}/comments/${commentId}`, {
method: 'DELETE',
});
}
// Likes API
async likePost(postId, likeData) {
return this.request(`/posts/${postId}/likes`, {
method: 'POST',
body: JSON.stringify(likeData),
});
}
async unlikePost(postId) {
return this.request(`/posts/${postId}/likes`, {
method: 'DELETE',
});
}
}
export default new ApiService();