import { http_delete_async, http_get_async, http_post_async } from "$lib/api/_fetch"; import { api_base, CookieNames } from "$lib/configuration"; import { is_known_problem } from "$lib/models/internal/KnownProblem"; import type { CreateAccountPayload, CreateAccountResponse, DeleteAccountResponse, IAccountService, LoginPayload, LoginResponse, Session, UpdateAccountPayload, UpdateAccountResponse } from "./abstractions/IAccountService"; export class AccountService implements IAccountService { session: Session; async login_async(payload: LoginPayload): Promise { const response = await http_post_async(api_base("_/account/login"), payload); return { isLoggedIn: response.ok }; } async logout_async(): Promise { const response = await http_get_async(api_base("_/account/logout")); if (!response.ok) { const deleteCookieResponse = await fetch("/delete-cookie?key=" + CookieNames.session); if (!deleteCookieResponse.ok) { throw new Error("Could neither logout nor delete session cookie."); } } return; } async create_account_async(payload: CreateAccountPayload): Promise { const response = await http_post_async(api_base("_/account/create"), payload); if (response.ok) return { isCreated: true }; if (is_known_problem(response)) return { isCreated: false, knownProblem: await response.json() } return { isCreated: false } } async delete_current_async(): Promise { const response = await http_delete_async(api_base("_/account/delete")); return { isDeleted: response.ok } } async update_current_async(payload: UpdateAccountPayload): Promise { const response = await http_post_async(api_base("_/account/update"), payload); if (response.ok) return { isUpdated: true }; if (is_known_problem(response)) return { isUpdated: false, knownProblem: await response.json() } return { isUpdated: false } } }