ionian/packages/client/src/state/api.ts

92 lines
2.1 KiB
TypeScript

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<RefreshResponse> {
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<LogoutResponse> {
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<LoginResponse> {
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;
}