Repository navigation
Expand file tree
/
Copy pathapi.jsx
More file actions
181 lines (161 loc) · 6.19 KB
/
Copy pathapi.jsx
File metadata and controls
181 lines (161 loc) · 6.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
/* DBLingo — frontend API client for the optional Vercel backend.
*
* The app is a static site (GitHub Pages). This module talks to the
* separate Vercel backend ONLY when API_BASE is set. If it's empty or any
* request fails, every helper degrades gracefully (returns null / []), so
* the app keeps working with its built-in stub leaderboard.
*
* To enable: set API_BASE to your deployed backend, e.g.
* const API_BASE = 'https://mongolingo-api.vercel.app/api';
* For local testing against `vercel dev`, use 'http://localhost:3000/api'.
*/
const API_BASE = (window.DBLINGO_API_BASE || '').replace(/\/$/, '');
const USER_ID_KEY = 'mongolingo.userId.v1';
function newUserId() {
return (window.crypto && crypto.randomUUID)
? crypto.randomUUID()
: 'u_' + Math.random().toString(36).slice(2) + Date.now().toString(36);
}
/** The current participant's id on this device. Each participant (session)
* gets their own id — see startNewUserSession(). */
function getUserId() {
try {
let id = localStorage.getItem(USER_ID_KEY);
if (!id) {
id = newUserId();
localStorage.setItem(USER_ID_KEY, id);
}
return id;
} catch (e) {
return 'u_anon';
}
}
/** Start a fresh participant on this device. The previous participant's
* player record and event scores stay on the server untouched, so a shared
* device ("Change path" → next person) never overwrites an earned score. */
function startNewUserSession() {
const id = newUserId();
try { localStorage.setItem(USER_ID_KEY, id); } catch (e) {}
return id;
}
function apiEnabled() {
return !!API_BASE;
}
async function apiFetch(path, options) {
if (!API_BASE) return null;
try {
const res = await fetch(API_BASE + path, {
headers: { 'Content-Type': 'application/json' },
...options
});
if (!res.ok) return null;
return await res.json();
} catch (e) {
return null;
}
}
async function registerUser({ name, company, email, pack, eventId }) {
if (!apiEnabled()) return null;
return apiFetch('/register', {
method: 'POST',
body: JSON.stringify({ userId: getUserId(), name, company, email: email || undefined, pack, eventId: eventId || undefined })
});
}
async function submitScore({ xp, leaves, streak, bestStreak, pack, name, company, eventId }) {
if (!apiEnabled()) return null;
return apiFetch('/leaderboard', {
method: 'POST',
body: JSON.stringify({ userId: getUserId(), xp, leaves, streak, bestStreak, pack, name, company, eventId: eventId || undefined })
});
}
async function fetchLeaderboard({ pack, eventId, limit = 10 } = {}) {
if (!apiEnabled()) return null;
const qs = new URLSearchParams();
if (eventId) qs.set('event', eventId);
else if (pack) qs.set('pack', pack);
if (limit) qs.set('limit', String(limit));
const data = await apiFetch('/leaderboard?' + qs.toString(), { method: 'GET' });
return data && Array.isArray(data.leaders) ? data.leaders : null;
}
/* ---------- Event leaderboards ----------
* Events are created by an admin (ADMIN_KEY on the backend). Players join
* through an invite link: <app url>?event=<eventId>. */
/** Resolve an event by id. Returns the event, or null if missing/unreachable. */
async function fetchEvent(eventId) {
if (!apiEnabled() || !eventId) return null;
const data = await apiFetch('/events?id=' + encodeURIComponent(eventId), { method: 'GET' });
return data && data.event ? data.event : null;
}
/** Admin calls surface errors (unlike player calls) so the form can show them. */
async function adminFetch(path, adminKey, options) {
if (!API_BASE) return { error: 'Backend is not configured (DBLINGO_API_BASE).' };
try {
const res = await fetch(API_BASE + path, {
...options,
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + adminKey }
});
const data = await res.json().catch(() => ({}));
if (!res.ok) return { error: data.error || ('Request failed (' + res.status + ')') };
return data;
} catch (e) {
return { error: 'Network error — is the backend reachable?' };
}
}
function createEvent(adminKey, { name, eventId, pack, startsAt, endsAt, qrImage }) {
return adminFetch('/events', adminKey, {
method: 'POST',
body: JSON.stringify({ name, eventId: eventId || undefined, pack: pack || undefined, startsAt: startsAt || undefined, endsAt: endsAt || undefined, qrImage: qrImage || undefined })
});
}
/** Admin: set / replace (data URL) or remove (null) an event's QR image. */
function updateEventQr(adminKey, eventId, qrImage) {
return adminFetch('/events?id=' + encodeURIComponent(eventId), adminKey, {
method: 'PATCH',
body: JSON.stringify({ qrImage: qrImage || null })
});
}
/* Shown on event leaderboards that have no custom QR image. */
const DEFAULT_EVENT_QR = 'assets/event-qr-default.png';
/** URL of an event's QR image: its custom upload, or the default QR. */
function getEventQrUrl(event) {
if (API_BASE && event && event.eventId && event.qrVersion) {
return API_BASE + '/events?id=' + encodeURIComponent(event.eventId) + '&qr=1&v=' + event.qrVersion;
}
return DEFAULT_EVENT_QR;
}
function listEvents(adminKey) {
return adminFetch('/events', adminKey, { method: 'GET' });
}
/** Admin only: an event's top players including private contact details (email).
* Never used by the public leaderboard. */
function fetchEventLeadersAdmin(adminKey, eventId, limit = 25) {
const qs = new URLSearchParams({ id: eventId, leaders: '1', limit: String(limit) });
return adminFetch('/events?' + qs.toString(), adminKey, { method: 'GET', cache: 'no-store' });
}
/** Shareable invite link for an event. Always built from the app root (not
* the current route), so a link copied on /leaderboard/ still lands
* invitees on the join flow. */
function getInviteLink(eventId) {
let url;
try { url = new URL('.', document.baseURI); } catch (e) { url = new URL(window.location.href); }
url.search = '';
url.hash = '';
if (eventId) url.searchParams.set('event', eventId);
return url.toString();
}
window.DBLingoAPI = {
apiEnabled,
getUserId,
startNewUserSession,
registerUser,
submitScore,
fetchLeaderboard,
fetchEvent,
createEvent,
updateEventQr,
getEventQrUrl,
DEFAULT_EVENT_QR,
listEvents,
fetchEventLeadersAdmin,
getInviteLink
};