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

59 lines
1.9 KiB
TypeScript

export interface UserData {
is_admin: number
kind: string
last_activity?: string
registration_date?: string
username: string
uuid: string
}
export default class ConquerUser {
private _isAdmin = false
private kind = "ConquerUser"
private lastActivity: string | null = null
private registrationDate: string | null = null
private username: string | null = null
private uuid: string | null = null
constructor(data: UserData) {
this.lastActivity = data.last_activity ?? null;
this.registrationDate = data.registration_date ?? null;
if (this.kind !== data.kind) {
throw new Error(`We cannot instance a user from a kind different to ${this.kind}.`)
}
this._isAdmin = !!data.is_admin || false
this.uuid = data.uuid
this.username = data.username
if (this.username === null || this.username === undefined) {
throw new Error('No username in user instance')
}
if (this.uuid === null || this.username === undefined) {
throw new Error('No uuid in user instance')
}
}
public static async getSelfUser(): Promise<ConquerUser | null> {
const urlUser = new URL('/conquer/user', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port)
try {
const response = await fetch(urlUser)
if (response.status !== 200) {
throw new Error('Invalid response fetching user.')
}
const userData = await response.json()
return new ConquerUser(userData)
} catch (error) {
console.error(error)
return null
}
}
public getUsername(): string {
if (this.username === null) {
throw new Error('User username cannot be null.')
}
return this.username
}
public isAdmin(): boolean {
return this._isAdmin
}
}