Modularize frontend: API helper module and cleaner app.js
This commit is contained in:
44
wwwroot/js/api.js
Normal file
44
wwwroot/js/api.js
Normal file
@@ -0,0 +1,44 @@
|
||||
const defaultHeaders = { "Content-Type": "application/json" };
|
||||
|
||||
async function request(path, { method = "GET", body, adminKey } = {}) {
|
||||
const res = await fetch(path, {
|
||||
method,
|
||||
headers: {
|
||||
...defaultHeaders,
|
||||
...(adminKey ? { "X-Admin-Key": adminKey } : {})
|
||||
},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
let msg = `${res.status}`;
|
||||
try {
|
||||
const data = await res.json();
|
||||
msg = data.error || JSON.stringify(data);
|
||||
} catch { /* ignore */ }
|
||||
throw new Error(msg);
|
||||
}
|
||||
return res.status === 204 ? null : res.json();
|
||||
}
|
||||
|
||||
export const api = {
|
||||
state: () => request("/api/state"),
|
||||
me: () => request("/api/me"),
|
||||
setName: (name) => request("/api/me/name", { method: "POST", body: { name } }),
|
||||
|
||||
mySuggestions: () => request("/api/suggestions/mine"),
|
||||
createSuggestion: (payload) => request("/api/suggestions", { method: "POST", body: payload }),
|
||||
deleteSuggestion: (id) => request(`/api/suggestions/${id}`, { method: "DELETE" }),
|
||||
allSuggestions: () => request("/api/suggestions/all"),
|
||||
|
||||
myVotes: () => request("/api/votes/mine"),
|
||||
vote: (suggestionId, score) => request("/api/votes", { method: "POST", body: { suggestionId, score } }),
|
||||
|
||||
results: () => request("/api/results"),
|
||||
};
|
||||
|
||||
export const adminApi = {
|
||||
setPhase: (phase, adminKey) => request("/api/admin/phase", { method: "POST", body: { phase }, adminKey }),
|
||||
reset: (adminKey) => request("/api/admin/reset", { method: "POST", adminKey }),
|
||||
factoryReset: (adminKey) => request("/api/admin/factory-reset", { method: "POST", adminKey }),
|
||||
};
|
||||
Reference in New Issue
Block a user