import type {Attachment, CaptchaData, Gender, LoginRequest, LoginResponse, RegisterRequest, UpdatePasswordRequest, User, UserAttachType} from "../types"; import {axios} from "./BaseAPI"; import CommonAPI from "./CommonAPI"; const BASE_URI = "/user"; type UserAttachmentOwner = { attachmentList?: readonly Attachment[]; }; type UpdateCurrentRequest = Omit, "gender"> & { gender?: Gender | ""; }; async function register(req: CaptchaData): Promise { return await axios.post(`${BASE_URI}/register`, req); } /** * 登录 * * @param req 验证码登录对象 * @returns LoginResponse */ async function login(req: CaptchaData): Promise { return await axios.post(`${BASE_URI}/login`, req); } /** * 验证是否已登录 * * @returns true 为已登录 */ async function loginByToken(): Promise { return await axios.post(`${BASE_URI}/login/token`); } async function logout(): Promise { return await axios.post(`${BASE_URI}/logout`); } async function updateCurrent(req: UpdateCurrentRequest): Promise { return await axios.post(`${BASE_URI}/current/update`, req); } async function updatePassword(req: UpdatePasswordRequest): Promise { return await axios.post(`${BASE_URI}/update/password`, req); } /** * 获取用户数据 * * @param id 用户 ID * @returns 用户数据 */ async function view(id: string): Promise { return await axios.post(`${BASE_URI}/view/${id}`); } function getAvatarURL(user?: UserAttachmentOwner) { if (user?.attachmentList) { return findAttachmentByType(user.attachmentList, "AVATAR"); } } function getWrapperURL(user?: UserAttachmentOwner) { if (user?.attachmentList) { return findAttachmentByType(user.attachmentList, "WRAPPER"); } } function findAttachmentByType(attachmentList: readonly Attachment[], ...types: UserAttachType[]) { for (let i = 0; i < attachmentList.length; i++) { const attachType = attachmentList[i].attachType as UserAttachType | undefined; const id = attachmentList[i].id; if (id && attachType && types.includes(attachType)) { return CommonAPI.getAttachmentReadAPI(id); } } } export default { register, login, loginByToken, logout, updateCurrent, updatePassword, view, getAvatarURL, getWrapperURL };