Files
fairhopper-sdk/javascript/fh_sdk.js
2023-05-11 19:54:23 +02:00

150 lines
3.5 KiB
JavaScript

class ValidationError extends Error {
constructor(message) {
if (!message) {
message = "ValidationError";
}
super(message);
this.name = "ValidationError";
}
}
class PlayerNotFoundError extends Error {
constructor(message) {
if (!message) {
message = "Player not found";
}
super(message);
this.name = "PlayerNotFoundError";
}
}
class PlayerInactiveError extends Error {
constructor(message) {
if (!message) {
message = "Player kicked out due to inactivity";
}
super(message);
this.name = "PlayerInactiveError";
}
}
class PositionError extends Error {
constructor(message) {
if (!message) {
message = "Position out of bounds or collision with an object";
}
super(message);
this.name = "PositionError";
}
}
const Direction = {
LEFT: "left",
RIGHT: "right",
UP: "up",
DOWN: "down",
};
class FairHopper {
constructor(host) {
this.host = host;
this.defaultHeaders = {
Accept: "application/json",
"Content-Type": "application/json",
};
}
formatUrl(path) {
return `${this.host}${path}`;
}
async ping() {
const r = await fetch(this.formatUrl("/ping"), {
headers: this.defaultHeaders,
});
return await r.json();
}
async startGame(playerName) {
const payload = {
player_name: playerName,
};
const r = await fetch(this.formatUrl("/game"), {
method: "post",
headers: this.defaultHeaders,
body: JSON.stringify(payload),
});
switch (r.status) {
case 422:
throw new ValidationError();
}
return await r.json();
}
async getGameInfo() {
const r = await fetch(this.formatUrl("/game"), {
headers: this.defaultHeaders,
});
return await r.json();
}
async getPlayerInfo(playerId) {
const r = await fetch(this.formatUrl(`/player/${playerId}`), {
headers: this.defaultHeaders,
});
switch (r.status) {
case 403:
throw new PlayerInactiveError();
case 404:
throw new PlayerNotFoundError();
case 422:
throw new ValidationError();
}
return await r.json();
}
async moveLeft(playerId) {
return await this.move(playerId, "left");
}
async moveRight(playerId) {
return await this.move(playerId, "right");
}
async moveUp(playerId) {
return await this.move(playerId, "up");
}
async moveDown(playerId) {
return await this.move(playerId, "down");
}
async move(playerId, direction) {
const url = this.formatUrl(`/player/${playerId}/move/${direction}`);
const r = await fetch(url, {
method: "post",
headers: this.defaultHeaders,
});
switch (r.status) {
case 403:
throw new PlayerInactiveError();
case 404:
throw new PlayerNotFoundError();
case 409:
throw new PositionError();
case 422:
throw new ValidationError();
}
return await r.json();
}
}
module.exports = {
FairHopper,
PlayerNotFoundError,
PlayerInactiveError,
PositionError,
Direction,
};