Some checks failed
Build and Push Docker Image / buildx (push) Has been cancelled
75 lines
1.9 KiB
JavaScript
75 lines
1.9 KiB
JavaScript
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, year, month) {
|
|
const params = new URLSearchParams();
|
|
if (year !== undefined && month !== undefined) {
|
|
params.append('year', year);
|
|
params.append('month', month);
|
|
}
|
|
const queryString = params.toString();
|
|
const path = queryString ? `/api/calendar?${queryString}` : '/api/calendar';
|
|
return request(server, path, { token });
|
|
}
|
|
|
|
|
|
export async function saveCalendar(server, token, markedDates, deletedDates) {
|
|
return request(server, '/api/calendar', {
|
|
method: 'POST',
|
|
token,
|
|
body: { markedDates, deletedDates }
|
|
});
|
|
}
|