lorem_ipsum/assets/src/service/score-service.js
2026-03-08 20:45:00 +01:00

80 lines
1.7 KiB
JavaScript

class ScoreService {
constructor(config) {
this.baseUrl = config.API_BASE_URL;
this.urlTail = "score";
}
async getScoreByName(username) {
// Note: When user does not exist, we get a 200 with empty array, not a 404
const response = await fetch(`${this.baseUrl}${this.urlTail}/${username}`, {
method: "GET",
});
let body = null;
try {
body = await response.json();
} catch {
console.error("Error in getScoreByName");
}
return {
status: response.status,
ok: response.ok,
body: body,
};
}
async postScore(username, password, score, time, text, userWrittenText) {
const response = await fetch(`${this.baseUrl}${this.urlTail}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Username": username,
"X-Password": password,
},
body: JSON.stringify({
score: score,
time: time,
text: text,
userWrittenText: userWrittenText,
}),
});
let body = null;
try {
body = await response.json();
} catch {
console.error("Error in postScore");
}
return {
status: response.status,
ok: response.ok,
body: body,
};
}
async deleteScore(username, password, scoreId) {
const response = await fetch(`${this.baseUrl}${this.urlTail}/${scoreId}`, {
method: "DELETE",
headers: {
"X-Username": username,
"X-Password": password,
},
});
let body = null;
try {
body = await response.json();
} catch {
console.error("Error in deleteScore");
}
return {
status: response.status,
ok: response.ok,
body: body,
};
}
}
window.ScoreService = ScoreService;