burguillos.info/js-src/conquer/team.ts

84 lines
2.7 KiB
TypeScript

import JsonSerializer from '@burguillosinfo/conquer/serializer';
import { JsonObject, JsonProperty } from 'typescript-json-serializer';
@JsonObject()
export default class ConquerTeam {
@JsonProperty()
private kind: string;
@JsonProperty()
private uuid: string;
@JsonProperty()
private name: string;
@JsonProperty()
private description: string;
@JsonProperty()
private points: number;
@JsonProperty()
private color: string;
public getName(): string {
return this.name;
}
public getDescription(): string {
return this.description;
}
public getColor(): string {
return this.color;
}
constructor(uuid: string, name: string, description: string, points: number, color: string) {
this.kind = 'ConquerTeam';
this.uuid = uuid;
this.name = name;
this.description = description;
this.points = points;
this.color = color;
}
public static async getTeam(uuid: string): Promise<ConquerTeam> {
const urlTeam = new URL('/conquer/team/' + uuid, window.location.protocol + '//' + window.location.hostname + ':' + window.location.port)
try {
const response = await fetch(urlTeam)
if (response.status !== 200) {
throw new Error('Invalid response fetching team.')
}
const teamData = await response.json()
let team = JsonSerializer.deserialize(teamData, ConquerTeam);
if (team === undefined) {
team = null;
}
if (!(team instanceof ConquerTeam)) {
throw new Error('Unable to parse team.');
}
return team;
} catch (error) {
console.error(error)
throw new Error('Unable to fetch Team.');
}
}
public static async getSelfTeam(): Promise<ConquerTeam | null> {
const urlTeam = new URL('/conquer/user/team', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port)
try {
const response = await fetch(urlTeam)
if (response.status !== 200) {
throw new Error('Invalid response fetching team.')
}
const teamData = await response.json()
let team = JsonSerializer.deserialize(teamData, ConquerTeam);
if (team === undefined) {
team = null;
}
if (team !== null && !(team instanceof ConquerTeam)) {
throw new Error('Unable to parse team.');
}
return team;
} catch (error) {
console.error(error)
throw new Error('Unable to fetch Team.');
}
}
}