Files
ToBePlayed-Frontend/src/utils/settings.js
T
lobo 3aed243e35
Build, Test & Push Frontend / quality-check (push) Successful in 47s
Build, Test & Push Frontend / docker (push) Successful in 22s
feat(ui): add people lists for game owners and community stats
2026-10-06 13:19:58 +02:00

70 lines
2.5 KiB
JavaScript

import {apiFetch} from './api.js';
import {storage} from './storage.js';
export const LANGUAGES = ['en', 'de'];
const LANGUAGE_STORAGE_KEY = 'tbp_language';
export const REQUEST_TIMEOUT_MS = 10000;
export const readCachedLanguage = () => {
const stored = storage.get(LANGUAGE_STORAGE_KEY);
return LANGUAGES.includes(stored) ? stored : null;
};
export const cacheLanguage = (language) => storage.set(LANGUAGE_STORAGE_KEY, language);
export const ME_URL = () => `${import.meta.env.VITE_API_URL}/api/users/me`;
/**
* GET /api/users/me on Auth. The caller handles the response status.
*/
export const fetchMe = () => apiFetch(ME_URL(), {
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
let queue = Promise.resolve();
/**
* PUT /api/users/settings on Auth with `changes`. That endpoint replaces all four fields, so each save first loads
* the saved ones; saves run one after another, from every page. The caller handles the response status.
*/
export const saveSettings = (changes) => {
const save = async () => {
const me = await fetchMe();
if (!me.ok) return me;
const data = await me.json();
return apiFetch(`${import.meta.env.VITE_API_URL}/api/users/settings`, {
method: 'PUT',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
useDarkTheme: !!data.settings?.useDarkTheme,
language: data.settings?.language ?? '',
displayName: data.displayName ?? null,
publicProfile: !!data.settings?.publicProfile,
...changes,
}),
// A hung request must not hold back the next saves.
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
};
const result = queue.then(save, save);
queue = result.catch(() => {});
return result;
};
/** PUT on Auth, 204: show (or hide) the user by name in owner lists. The caller handles the response status. */
export const saveOwnerLists = (enabled) =>
apiFetch(`${import.meta.env.VITE_API_URL}/api/users/settings/owner-lists`, {
method: 'PUT',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({enabled}),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
/** PUT on Auth, 204: the welcome page was seen. The caller handles the response status. */
export const markWelcomeSeen = () =>
apiFetch(`${import.meta.env.VITE_API_URL}/api/users/settings/welcome-seen`, {
method: 'PUT',
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});