import { APIClient } from "./ApiClient"; interface FamilyAPI { user_id: number; family_id: number; name: string; time_create: number; is_admin: boolean; invitation_code: string; count_members: number; count_admins: number; } export class Family implements FamilyAPI { user_id: number; family_id: number; name: string; time_create: number; is_admin: boolean; invitation_code: string; count_members: number; count_admins: number; constructor(f: FamilyAPI) { this.user_id = f.user_id; this.family_id = f.family_id; this.name = f.name; this.time_create = f.time_create; this.is_admin = f.is_admin; this.invitation_code = f.invitation_code; this.count_members = f.count_members; this.count_admins = f.count_admins; } /** * Check if the current user user can leave a family */ get CanLeave(): boolean { return !this.is_admin || this.count_admins > 1; } /** * Get application URL for family */ URL(uri?: string): string { return `/family/${this.family_id}/${uri ?? ""}`; } /** * Get base family URL */ get BaseURL(): string { return this.URL(""); } } export enum JoinFamilyResult { TooManyRequests, InvalidCode, AlreadyMember, Error, Success, } export class FamilyApi { /** * Create a new family */ static async CreateFamily(name: string): Promise { await APIClient.exec({ method: "POST", uri: "/family/create", jsonData: { name: name }, }); } /** * Join an existing family */ static async JoinFamily(code: string): Promise { const res = await APIClient.exec({ method: "POST", uri: "/family/join", allowFail: true, jsonData: { code: code }, }); if (res.status >= 200 && res.status < 300) return JoinFamilyResult.Success; switch (res.status) { case 429: return JoinFamilyResult.TooManyRequests; case 404: return JoinFamilyResult.InvalidCode; case 409: return JoinFamilyResult.AlreadyMember; default: return JoinFamilyResult.Error; } } /** * Get the list of families */ static async GetList(): Promise { return ( await APIClient.exec({ method: "GET", uri: "/family/list", }) ).data.map((f: FamilyAPI) => new Family(f)); } /** * Get information about a single family */ static async GetSingle(id: number): Promise { const res = await APIClient.exec({ method: "GET", uri: `/family/${id}`, }); return new Family(res.data); } /** * Attempt to leave a family */ static async LeaveFamily(id: number): Promise { await APIClient.exec({ method: "POST", uri: `/family/${id}/leave`, }); } }