50 lines
1.5 KiB
JavaScript
50 lines
1.5 KiB
JavaScript
// public/js/api.js - wrappers around fetch. All network calls go here.
|
|
|
|
async function request(path, options = {}) {
|
|
const res = await fetch(path, {
|
|
headers: { 'Content-Type': 'application/json', ...(options.headers || {}) },
|
|
credentials: 'same-origin',
|
|
...options,
|
|
});
|
|
const body = await res.json().catch(() => ({}));
|
|
if (!res.ok) {
|
|
const msg = body?.error || `Request failed (${res.status})`;
|
|
throw new Error(msg);
|
|
}
|
|
return body;
|
|
}
|
|
|
|
export const api = {
|
|
me: () => request('/api/me'),
|
|
login: (screenName, password) => request('/api/login', {
|
|
method: 'POST',
|
|
body: JSON.stringify({ screenName, password }),
|
|
}),
|
|
logout: () => request('/api/logout', { method: 'POST', body: '{}' }),
|
|
sendIM: (to, text) => request('/api/im', {
|
|
method: 'POST',
|
|
body: JSON.stringify({ to, text }),
|
|
}),
|
|
joinRoom: (room, exchange = 4) => request('/api/chat/join', {
|
|
method: 'POST',
|
|
body: JSON.stringify({ room, exchange }),
|
|
}),
|
|
sendChat: (room, text) => request('/api/chat/send', {
|
|
method: 'POST',
|
|
body: JSON.stringify({ room, text }),
|
|
}),
|
|
acceptChat: (roomId) => request('/api/chat/accept', {
|
|
method: 'POST',
|
|
body: JSON.stringify({ roomId }),
|
|
}),
|
|
leaveRoom: (room) => request('/api/chat/leave', {
|
|
method: 'POST',
|
|
body: JSON.stringify({ room }),
|
|
}),
|
|
buddies: () => request('/api/buddies'),
|
|
addBuddy: (screenName) => request('/api/buddies', {
|
|
method: 'POST',
|
|
body: JSON.stringify({ screenName }),
|
|
}),
|
|
searchUsers: (q) => request(`/api/users?q=${encodeURIComponent(q)}`),
|
|
};
|