create a frontend with a main menu
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:3000'
|
||||
|
||||
async function request(path, { method = 'GET', body, token, formData } = {}) {
|
||||
const headers = {}
|
||||
if (token) headers['Authorization'] = `Bearer ${token}`
|
||||
if (body && !formData) headers['Content-Type'] = 'application/json'
|
||||
|
||||
const res = await fetch(`${API_URL}${path}`, {
|
||||
method,
|
||||
headers,
|
||||
body: formData ? formData : body ? JSON.stringify(body) : undefined,
|
||||
})
|
||||
|
||||
const data = await res.json().catch(() => ({}))
|
||||
if (!res.ok) {
|
||||
const message = data.errors ? data.errors.join(', ') : data.error || 'Ошибка сервера'
|
||||
throw new ApiError(message, res.status)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(message, status) {
|
||||
super(message)
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
export const api = {
|
||||
login: (nickname, password) =>
|
||||
request('/api/login', { method: 'POST', body: { nickname, password } }),
|
||||
|
||||
register: (nickname, password, avatarFile) => {
|
||||
const formData = new FormData()
|
||||
formData.append('user[nickname]', nickname)
|
||||
formData.append('user[password]', password)
|
||||
if (avatarFile) formData.append('user[avatar]', avatarFile)
|
||||
return request('/api/register', { method: 'POST', formData })
|
||||
},
|
||||
|
||||
me: (token) => request('/api/me', { token }),
|
||||
|
||||
logout: (token) => request('/api/logout', { method: 'DELETE', token }),
|
||||
}
|
||||
Reference in New Issue
Block a user