import axios from 'axios'; import * as r from './retry.js'; export const apiServer = axios.create({ baseURL: '/api/', }); export async function boot() { return apiServer.get('/boot').catch(responseError); } export async function setup(name, password) { return await apiServer.post('/setup', { name, password }).catch(responseError); } export async function logIn(name, password) { return await apiServer.post('/auth/login', { name, password }).catch(responseError); } export async function logOut() { return await apiServer.post('/auth/logout', {}).catch(responseError); } export async function changePassword(password, to) { return await apiServer.post('/password', { password, to }).catch(responseError); } export async function createConversation(name) { return await apiServer.post('/conversations', { name }).catch(responseError); } export async function sendToConversation(conversationId, body) { return await apiServer.post(`/conversations/${conversationId}`, { body }).catch(responseError); } export async function deleteMessage(messageId) { return await apiServer.delete(`/messages/${messageId}`, {}).catch(responseError); } export async function createInvite() { return await apiServer.post(`/invite`, {}).catch(responseError); } export async function getInvite(inviteId) { return await apiServer.get(`/invite/${inviteId}`).catch(responseError); } export async function acceptInvite(inviteId, name, password) { return apiServer .post(`/invite/${inviteId}`, { name, password, }) .catch(responseError); } export async function createPushSubscription(subscription, vapid) { return apiServer.post('/push/subscribe', { subscription, vapid }).catch(responseError); } export function subscribeToEvents(resumePoint) { const eventsUrl = apiServer.getUri({ url: '/events', params: { resume_point: resumePoint, }, }); return new EventSource(eventsUrl); } export class LoggedOut extends Error {} export class SetupRequired extends Error {} export async function retry(op) { return await r.retry(op, isRetryable, r.timedDelay(5000)); } function responseError(err) { if (err.response) { switch (err.response.status) { case 401: throw new LoggedOut(); case 503: throw new SetupRequired(); } } throw err; } function isRetryable(err) { // See for a breakdown of this logic. // Any error with a response is non-retryable. The server responded; we get to act on that // response. We don't do anything special for 5xx-series responses yet, but they might one day be // retryable too. if (err.response) { return false; } // Any error with no response and a request is probably from the network side of things, and is // retryable. if (err.request) { return true; } // Anything with neither is unexpected enough that we should not try it. return false; }