cursor done.
This commit is contained in:
66
public/js/api.js
Normal file
66
public/js/api.js
Normal file
@@ -0,0 +1,66 @@
|
||||
export class ApiError extends Error {
|
||||
constructor(message, status) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
async function request(server, path, { method = 'GET', body, token } = {}) {
|
||||
try {
|
||||
const headers = { 'Content-Type': 'application/json' };
|
||||
if (token) {
|
||||
headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const response = await fetch(`${server}${path}`, {
|
||||
method,
|
||||
headers,
|
||||
body: body ? JSON.stringify(body) : undefined
|
||||
});
|
||||
|
||||
const data = await response.json().catch(() => ({}));
|
||||
|
||||
if (!response.ok || data.success === false) {
|
||||
const message = data.error || data.message || response.statusText;
|
||||
throw new ApiError(message, response.status);
|
||||
}
|
||||
|
||||
return data;
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError) {
|
||||
throw error;
|
||||
}
|
||||
throw new ApiError('无法连接到服务器,请确认服务已启动', 0);
|
||||
}
|
||||
}
|
||||
|
||||
export async function register(server, username, password) {
|
||||
return request(server, '/api/auth/register', {
|
||||
method: 'POST',
|
||||
body: { username, password }
|
||||
});
|
||||
}
|
||||
|
||||
export async function login(server, username, password) {
|
||||
return request(server, '/api/auth/login', {
|
||||
method: 'POST',
|
||||
body: { username, password }
|
||||
});
|
||||
}
|
||||
|
||||
export async function fetchCurrentUser(server, token) {
|
||||
return request(server, '/api/auth/me', { token });
|
||||
}
|
||||
|
||||
export async function fetchCalendar(server, token) {
|
||||
return request(server, '/api/calendar', { token });
|
||||
}
|
||||
|
||||
export async function saveCalendar(server, token, markedDates) {
|
||||
return request(server, '/api/calendar', {
|
||||
method: 'POST',
|
||||
token,
|
||||
body: { markedDates }
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user