import { makeApiUrl } from "../hook/fetcher.ts"; import { LoginRequest } from "dbtype/mod.ts"; export type LoginResponse = { username: string; permission: string[]; accessExpired: number; }; export type LogoutResponse = { ok: boolean; username: string; permission: string[]; }; export type RefreshResponse = LoginResponse & { refresh: boolean; }; export type ErrorFormat = { code: number; message: string; detail?: string; }; export class ApiError extends Error { public readonly code: number; public readonly detail?: string; constructor(error: ErrorFormat) { super(error.message); this.name = "ApiError"; this.code = error.code; this.detail = error.detail; } } export async function refreshService(): Promise { const u = makeApiUrl("/api/user/refresh"); const res = await fetch(u, { method: "POST", credentials: "include", }); const b = await res.json(); if (!res.ok) { throw new ApiError(b as ErrorFormat); } return b as RefreshResponse; } export async function logoutService(): Promise { const u = makeApiUrl("/api/user/logout"); const req = await fetch(u, { method: "POST", credentials: "include", }); const b = await req.json(); if (!req.ok) { throw new ApiError(b as ErrorFormat); } return b as LogoutResponse; } export async function loginService(userLoginInfo: LoginRequest): Promise { const u = makeApiUrl("/api/user/login"); const res = await fetch(u, { method: "POST", body: JSON.stringify(userLoginInfo), headers: { "content-type": "application/json" }, credentials: "include", }); const b = await res.json(); if (!res.ok) { throw new ApiError(b as ErrorFormat); } return b as LoginResponse; } export async function resetPasswordService(username: string, oldpassword: string, newpassword: string): Promise<{ ok: boolean }> { const u = makeApiUrl("/api/user/reset"); const res = await fetch(u, { method: "POST", body: JSON.stringify({ username, oldpassword, newpassword }), headers: { "content-type": "application/json" }, credentials: "include", }); const b = await res.json(); if (!res.ok) { throw new ApiError(b as ErrorFormat); } return b; }