58 lines
1.5 KiB
JavaScript
58 lines
1.5 KiB
JavaScript
// api.js - small backend client for the static frontend
|
|
|
|
const BASE_URL = `${window.location.origin}/backend/index.php`;
|
|
|
|
async function request(action, payload = null) {
|
|
const options = payload
|
|
? {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(payload),
|
|
}
|
|
: {};
|
|
const response = await fetch(`${BASE_URL}?action=${action}`, options);
|
|
const data = await response.json();
|
|
|
|
if (!response.ok || !data.ok) {
|
|
throw new Error(data.error || "Backend request failed.");
|
|
}
|
|
|
|
return data;
|
|
}
|
|
|
|
function get(action, params = {}) {
|
|
const query = new URLSearchParams({ action, ...params });
|
|
return fetch(`${BASE_URL}?${query.toString()}`)
|
|
.then((response) => response.json().then((data) => ({ response, data })))
|
|
.then(({ response, data }) => {
|
|
if (!response.ok || !data.ok) {
|
|
throw new Error(data.error || "Backend request failed.");
|
|
}
|
|
return data;
|
|
});
|
|
}
|
|
|
|
export function createLobby(lobbyName) {
|
|
return request("createLobby", { lobbyName });
|
|
}
|
|
|
|
export function joinLobby(lobbyName, playerName) {
|
|
return request("joinLobby", { lobbyName, playerName });
|
|
}
|
|
|
|
export function leaveLobby(lobbyName, playerName) {
|
|
return request("leaveLobby", { lobbyName, playerName });
|
|
}
|
|
|
|
export function submitScore(payload) {
|
|
return request("submitScore", payload);
|
|
}
|
|
|
|
export function getLeaderboard(lobbyName) {
|
|
return get("getLeaderboard", { lobbyName });
|
|
}
|
|
|
|
export function getLobby(lobbyName) {
|
|
return get("getLobby", { lobbyName });
|
|
}
|