init project
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
import type { Article } from "../types";
|
||||
import { axios } from "./BaseAPI";
|
||||
|
||||
export const ArticleAPI = {
|
||||
/**
|
||||
* 获取文章
|
||||
*
|
||||
* @param id 文章 ID
|
||||
* @returns 文章数据
|
||||
*/
|
||||
async view(id: string): Promise<Article> {
|
||||
return axios.get(`/article/${id}`);
|
||||
},
|
||||
/**
|
||||
* 喜欢文章,后端有限调用,1240ms 一次
|
||||
*
|
||||
* @param id 文章 ID
|
||||
* @returns 最新喜欢数量
|
||||
*/
|
||||
async like(id: string): Promise<number> {
|
||||
return axios.get(`/article/like/${id}`);
|
||||
}
|
||||
};
|
||||
|
||||
export default ArticleAPI;
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { Attachment, BizIdUpdate, TempFile } from "../types";
|
||||
import { axios, getBaseURI } from "./BaseAPI";
|
||||
|
||||
const BASE_URI = "/attach";
|
||||
|
||||
export const AttachmentAPI = {
|
||||
/**
|
||||
* 上传临时附件
|
||||
*
|
||||
* @param file 文件或文件列表
|
||||
* @param ttl 有效期
|
||||
* @returns 临时附件列表
|
||||
*/
|
||||
async upload(file: File | File[], ttl?: string): Promise<TempFile[]> {
|
||||
const formData = new FormData();
|
||||
const fileList = Array.isArray(file) ? file : [file];
|
||||
for (const item of fileList) {
|
||||
formData.append("file", item);
|
||||
}
|
||||
if (ttl) {
|
||||
formData.append("ttl", ttl);
|
||||
}
|
||||
return await axios.post(`${BASE_URI}/temp/upload`, formData);
|
||||
},
|
||||
/**
|
||||
* 按业务差分更新附件
|
||||
*
|
||||
* @param req 更新请求
|
||||
*/
|
||||
async updateByBizId(req: BizIdUpdate): Promise<void> {
|
||||
return await axios.post(`${BASE_URI}/update/biz/id`, req);
|
||||
},
|
||||
/**
|
||||
* 按业务查询附件列表
|
||||
*
|
||||
* @param bizType 业务类型
|
||||
* @param bizId 业务 ID
|
||||
* @param attachTypeList 附件类型列表
|
||||
*/
|
||||
async listByBizId(bizType: string, bizId: string, attachTypeList?: string[]): Promise<Attachment[]> {
|
||||
return await axios.get(`${BASE_URI}/list/biz/id`, {
|
||||
params: {
|
||||
bizType,
|
||||
bizId,
|
||||
attachTypeList
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
getReadURL(id: string): string {
|
||||
return `${getBaseURI()}${BASE_URI}/read/${id}`;
|
||||
},
|
||||
|
||||
getTempReadURL(id: string): string {
|
||||
return `${getBaseURI()}${BASE_URI}/temp/read?id=${id}`;
|
||||
}
|
||||
};
|
||||
|
||||
export default AttachmentAPI;
|
||||
@@ -0,0 +1,24 @@
|
||||
import Network from "../utils/Network";
|
||||
|
||||
let serviceAxios: any | null = null;
|
||||
|
||||
function getServiceAxios(): any {
|
||||
if (serviceAxios === null) {
|
||||
serviceAxios = Network.axios;
|
||||
}
|
||||
return serviceAxios;
|
||||
}
|
||||
|
||||
export const axios = new Proxy({} as any, {
|
||||
get(_target: any, prop: string | symbol, receiver: any): any {
|
||||
return Reflect.get(getServiceAxios(), prop, receiver);
|
||||
}
|
||||
});
|
||||
|
||||
export function getBaseURI(): string {
|
||||
const baseURL = axios.defaults.baseURL;
|
||||
if (!baseURL || baseURL === "undefined") {
|
||||
return "";
|
||||
}
|
||||
return baseURL.replace(/\/$/, "");
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { CaptchaData, Comment, Page, PageResult } from "../types";
|
||||
import { axios } from "./BaseAPI";
|
||||
|
||||
const BASE_URI = "/comment";
|
||||
|
||||
export const CommentAPI = {
|
||||
async page(page: Page<Comment>): Promise<PageResult<Comment>> {
|
||||
return axios.post(`${BASE_URI}/list`, page);
|
||||
},
|
||||
async create(captchaData: CaptchaData<Comment>): Promise<void> {
|
||||
return axios.post(`${BASE_URI}/create`, captchaData);
|
||||
}
|
||||
};
|
||||
|
||||
export default CommentAPI;
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { CaptchaResult } from "../types";
|
||||
import { axios, getBaseURI } from "./BaseAPI";
|
||||
|
||||
export const CommonAPI = {
|
||||
|
||||
getCaptchaAPI(): string {
|
||||
return `${getBaseURI()}/captcha`;
|
||||
},
|
||||
|
||||
async captcha(width: number, height: number): Promise<CaptchaResult> {
|
||||
return await axios.get(`/captcha?width=${width}&height=${height}`);
|
||||
},
|
||||
};
|
||||
|
||||
export default CommonAPI;
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { Developer } from "../types";
|
||||
import { axios } from "./BaseAPI";
|
||||
|
||||
const BASE_URI = "/git/developer";
|
||||
|
||||
export const DeveloperAPI = {
|
||||
async get(): Promise<Developer> {
|
||||
return axios.post(`${BASE_URI}`);
|
||||
}
|
||||
};
|
||||
|
||||
export default DeveloperAPI;
|
||||
@@ -0,0 +1,83 @@
|
||||
import { axios } from "./BaseAPI";
|
||||
import type { CaptchaData, Notify, NotifyDetail, NotifyManagementItem, Page, PageResult } from "../types";
|
||||
|
||||
const BASE_URI = "/notify/internal";
|
||||
const MANAGEMENT_BASE_URI = "/notify/management";
|
||||
|
||||
export const NotifyAPI = {
|
||||
|
||||
/** 管理端创建并发送通知。 */
|
||||
async create(notify: Notify): Promise<Notify> {
|
||||
return await axios.post("/notify/create", notify);
|
||||
},
|
||||
|
||||
/** 查询当前管理用户创建的通知列表。 */
|
||||
async listManagement(page?: Page<Notify>): Promise<PageResult<NotifyManagementItem>> {
|
||||
return await axios.post(`${MANAGEMENT_BASE_URI}/list`, page);
|
||||
},
|
||||
|
||||
/** 查询管理端通知详情及收件人。 */
|
||||
async managementDetail(id: string): Promise<Notify> {
|
||||
return await axios.post(`${MANAGEMENT_BASE_URI}/detail`, undefined, {
|
||||
params: { id }
|
||||
});
|
||||
},
|
||||
|
||||
/** 删除管理端通知。 */
|
||||
async managementDelete(id: string): Promise<void> {
|
||||
await axios.post(`${MANAGEMENT_BASE_URI}/delete`, undefined, {
|
||||
params: { id }
|
||||
});
|
||||
},
|
||||
|
||||
/** 取消管理端尚未发送的通知。 */
|
||||
async managementCancel(id: string): Promise<void> {
|
||||
await axios.post(`${MANAGEMENT_BASE_URI}/cancel`, undefined, {
|
||||
params: { id }
|
||||
});
|
||||
},
|
||||
|
||||
async smsSend(captchaData: CaptchaData<Notify>) {
|
||||
return await axios.post("/notify/sms/captcha/create", captchaData);
|
||||
},
|
||||
|
||||
/** 查询当前用户的站内通知详情。 */
|
||||
async internalDetail(id: string): Promise<NotifyDetail> {
|
||||
return await axios.post(`${BASE_URI}/detail`, undefined, {
|
||||
params: { id }
|
||||
});
|
||||
},
|
||||
|
||||
/** 查询当前用户的站内通知。 */
|
||||
async listInternal(page?: Page<NotifyDetail>, unreadOnly = false): Promise<PageResult<NotifyDetail>> {
|
||||
return await axios.post(`${BASE_URI}/internal`, page, {
|
||||
params: { unreadOnly }
|
||||
});
|
||||
},
|
||||
|
||||
/** 查询当前用户未读站内通知数量。 */
|
||||
async countUnreadInternal(): Promise<number> {
|
||||
return await axios.post(`${BASE_URI}/unread/count`);
|
||||
},
|
||||
|
||||
/** 标记当前用户的一条站内通知已读。 */
|
||||
async markInternalRead(id: string): Promise<void> {
|
||||
await axios.post(`${BASE_URI}/read`, undefined, {
|
||||
params: { id }
|
||||
});
|
||||
},
|
||||
|
||||
/** 删除当前用户的一条站内通知。 */
|
||||
async deleteInternal(id: string): Promise<void> {
|
||||
await axios.post(`${BASE_URI}/delete`, undefined, {
|
||||
params: { id }
|
||||
});
|
||||
},
|
||||
|
||||
/** 标记当前用户全部站内通知已读。 */
|
||||
async markAllInternalRead(): Promise<void> {
|
||||
await axios.post(`${BASE_URI}/read/all`);
|
||||
}
|
||||
};
|
||||
|
||||
export default NotifyAPI;
|
||||
@@ -0,0 +1,29 @@
|
||||
import { axios } from "./BaseAPI";
|
||||
import type { ModuleCode, Page, PageResult, Permission, PermissionPayload } from "../types";
|
||||
|
||||
const BASE_URI = "/user/permission";
|
||||
|
||||
export const PermissionAPI = {
|
||||
async list(req: Page<Permission>): Promise<PageResult<Permission>> {
|
||||
return axios.post(`${BASE_URI}/list`, req);
|
||||
},
|
||||
async create(req: PermissionPayload): Promise<void> {
|
||||
return axios.post(`${BASE_URI}/create`, req);
|
||||
},
|
||||
async update(req: PermissionPayload): Promise<void> {
|
||||
return axios.post(`${BASE_URI}/update`, req);
|
||||
},
|
||||
async remove(id: string): Promise<void> {
|
||||
return axios.post(`${BASE_URI}/delete`, undefined, {
|
||||
params: { id }
|
||||
});
|
||||
},
|
||||
/** 查询当前登录用户在指定模块内可转授的权限。 */
|
||||
async grantableList(moduleCode: ModuleCode): Promise<Permission[]> {
|
||||
return await axios.post(`${BASE_URI}/grantable/list`, undefined, {
|
||||
params: { moduleCode }
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export default PermissionAPI;
|
||||
@@ -0,0 +1,100 @@
|
||||
import { axios } from "./BaseAPI";
|
||||
import type { ModuleCode, Page, PageResult, Permission, Role, RolePayload, AuthorizeUserRole } from "../types";
|
||||
|
||||
const BASE_URI = "/user/role";
|
||||
|
||||
export const RoleAPI = {
|
||||
async list(req: Page<Role>): Promise<PageResult<Role>> {
|
||||
return axios.post(`${BASE_URI}/list`, req);
|
||||
},
|
||||
async detail(id: string): Promise<Role> {
|
||||
return axios.post(`${BASE_URI}/detail`, undefined, {
|
||||
params: { id }
|
||||
});
|
||||
},
|
||||
async create(req: RolePayload): Promise<void> {
|
||||
return axios.post(`${BASE_URI}/create`, req);
|
||||
},
|
||||
async update(req: RolePayload): Promise<void> {
|
||||
return axios.post(`${BASE_URI}/update`, req);
|
||||
},
|
||||
async remove(id: string): Promise<void> {
|
||||
return axios.post(`${BASE_URI}/delete`, undefined, {
|
||||
params: { id }
|
||||
});
|
||||
},
|
||||
/** 查询当前登录用户在模块内可管理的角色。 */
|
||||
async manageableList(moduleCode: ModuleCode): Promise<Role[]> {
|
||||
return await axios.post(`${BASE_URI}/manageable/list`, undefined, {
|
||||
params: { moduleCode }
|
||||
});
|
||||
},
|
||||
/** 查询当前登录用户在模块内可授权给账号的角色。 */
|
||||
async grantableList(moduleCode: ModuleCode): Promise<Role[]> {
|
||||
return await axios.post(`${BASE_URI}/grantable/list`, undefined, {
|
||||
params: { moduleCode }
|
||||
});
|
||||
},
|
||||
/** 查询当前登录用户直属角色详情,不按可管理范围过滤。 */
|
||||
async currentDetailList(moduleCode?: ModuleCode): Promise<Role[]> {
|
||||
return await axios.post(`${BASE_URI}/current/detail/list`, undefined, {
|
||||
params: { moduleCode }
|
||||
});
|
||||
},
|
||||
/** 查询当前登录用户可以给目标角色配置的直接权限 P 候选项。 */
|
||||
async grantablePermissionList(roleId: string): Promise<Permission[]> {
|
||||
return await axios.post(`${BASE_URI}/permission/grantable/list`, undefined, {
|
||||
params: { roleId }
|
||||
});
|
||||
},
|
||||
/** 查询目标角色当前可继续转授的权限 D。 */
|
||||
async delegationList(roleId: string): Promise<Permission[]> {
|
||||
return await axios.post(`${BASE_URI}/delegation/list`, undefined, {
|
||||
params: { roleId }
|
||||
});
|
||||
},
|
||||
/** 查询当前登录用户可以给目标角色配置的 D 候选项。 */
|
||||
async grantableDelegationList(roleId: string): Promise<Permission[]> {
|
||||
return await axios.post(`${BASE_URI}/delegation/grantable/list`, undefined, {
|
||||
params: { roleId }
|
||||
});
|
||||
},
|
||||
/** 覆盖保存目标角色可继续转授的权限 D。 */
|
||||
async updateDelegation(req: Pick<RolePayload, "id" | "delegationPermissionIdList">): Promise<void> {
|
||||
await axios.post(`${BASE_URI}/delegation/update`, req);
|
||||
},
|
||||
/** 查询目标角色可选管理父级。 */
|
||||
async parentGrantableList(roleId: string): Promise<Role[]> {
|
||||
return await axios.post(`${BASE_URI}/parent/grantable/list`, undefined, {
|
||||
params: { roleId }
|
||||
});
|
||||
},
|
||||
/** 查询创建模块角色时可选的管理父级。 */
|
||||
async createParentGrantableList(moduleCode: ModuleCode): Promise<Role[]> {
|
||||
return await axios.post(`${BASE_URI}/parent/create/grantable/list`, undefined, {
|
||||
params: { moduleCode }
|
||||
});
|
||||
},
|
||||
/** 保存目标角色管理父级。 */
|
||||
async updateParent(req: Pick<RolePayload, "id" | "parentRoleId">): Promise<void> {
|
||||
await axios.post(`${BASE_URI}/parent/update`, req);
|
||||
},
|
||||
async authorizedList(userId: string, moduleCode?: ModuleCode): Promise<Role[]> {
|
||||
return axios.post(`${BASE_URI}/authorized/list`, undefined, {
|
||||
params: {
|
||||
userId,
|
||||
moduleCode
|
||||
}
|
||||
});
|
||||
},
|
||||
async authorize(req: AuthorizeUserRole): Promise<void> {
|
||||
return axios.post(`${BASE_URI}/authorized/create`, req);
|
||||
},
|
||||
async authorizedPermission(userId: string): Promise<Permission[]> {
|
||||
return axios.post(`${BASE_URI}/authorized/permission`, undefined, {
|
||||
params: { userId }
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export default RoleAPI;
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { Setting } from "../types";
|
||||
import { axios } from "./BaseAPI";
|
||||
|
||||
const BASE_URI = "/setting";
|
||||
|
||||
export const SettingAPI = {
|
||||
|
||||
/**
|
||||
* 查询公开配置映射
|
||||
*
|
||||
* @param bizType 业务类型
|
||||
* @param bizId 业务 ID,可为空
|
||||
* @param code 配置代码列表,可为空
|
||||
*/
|
||||
async map(bizType: string, bizId?: string, code?: string[]): Promise<Record<string, Setting>> {
|
||||
return await axios.get(`${BASE_URI}/map`, {
|
||||
params: {
|
||||
bizType,
|
||||
bizId,
|
||||
code
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export default SettingAPI;
|
||||
@@ -0,0 +1,94 @@
|
||||
import type {
|
||||
Attachment,
|
||||
CaptchaData,
|
||||
Gender,
|
||||
LoginRequest,
|
||||
LoginResponse,
|
||||
RegisterRequest,
|
||||
SmsLoginRequest,
|
||||
UpdatePasswordRequest,
|
||||
User,
|
||||
UserAttachType
|
||||
} from "../types";
|
||||
import { axios } from "./BaseAPI";
|
||||
import AttachmentAPI from "./AttachmentAPI";
|
||||
|
||||
const BASE_URI = "/user";
|
||||
type UserAttachmentOwner = {
|
||||
attachmentList?: readonly Attachment[];
|
||||
};
|
||||
type UpdateCurrentRequest = Omit<Partial<User>, "gender"> & {
|
||||
gender?: Gender | "";
|
||||
};
|
||||
|
||||
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 AttachmentAPI.getReadURL(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const UserAPI = {
|
||||
async register(req: CaptchaData<RegisterRequest>): Promise<LoginResponse> {
|
||||
return await axios.post(`${BASE_URI}/register`, req);
|
||||
},
|
||||
/**
|
||||
* 登录
|
||||
*
|
||||
* @param req 验证码登录对象
|
||||
* @returns LoginResponse
|
||||
*/
|
||||
async login(req: CaptchaData<LoginRequest>): Promise<LoginResponse> {
|
||||
return await axios.post(`${BASE_URI}/login`, req);
|
||||
},
|
||||
/**
|
||||
* 短信验证码登录
|
||||
*
|
||||
* @param req 短信验证码登录请求
|
||||
* @returns LoginResponse
|
||||
*/
|
||||
async loginBySms(req: SmsLoginRequest): Promise<LoginResponse> {
|
||||
return await axios.post(`${BASE_URI}/login/sms`, req);
|
||||
},
|
||||
/**
|
||||
* 验证是否已登录
|
||||
*
|
||||
* @returns true 为已登录
|
||||
*/
|
||||
async loginByToken(): Promise<LoginResponse> {
|
||||
return await axios.post(`${BASE_URI}/login/token`);
|
||||
},
|
||||
async logout(): Promise<void> {
|
||||
return await axios.post(`${BASE_URI}/logout`);
|
||||
},
|
||||
async updateCurrent(req: UpdateCurrentRequest): Promise<LoginResponse> {
|
||||
return await axios.post(`${BASE_URI}/current/update`, req);
|
||||
},
|
||||
async updatePassword(req: UpdatePasswordRequest): Promise<void> {
|
||||
return await axios.post(`${BASE_URI}/update/password`, req);
|
||||
},
|
||||
/**
|
||||
* 获取用户数据
|
||||
*
|
||||
* @param id 用户 ID
|
||||
* @returns 用户数据
|
||||
*/
|
||||
async view(id: string): Promise<User> {
|
||||
return await axios.post(`${BASE_URI}/view/${id}`);
|
||||
},
|
||||
getAvatarURL(user?: UserAttachmentOwner) {
|
||||
if (user?.attachmentList) {
|
||||
return findAttachmentByType(user.attachmentList, "AVATAR");
|
||||
}
|
||||
},
|
||||
getWrapperURL(user?: UserAttachmentOwner) {
|
||||
if (user?.attachmentList) {
|
||||
return findAttachmentByType(user.attachmentList, "WRAPPER");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export default UserAPI;
|
||||
@@ -0,0 +1,10 @@
|
||||
export { ArticleAPI } from "./ArticleAPI";
|
||||
export { AttachmentAPI } from "./AttachmentAPI";
|
||||
export { CommentAPI } from "./CommentAPI";
|
||||
export { CommonAPI } from "./CommonAPI";
|
||||
export { DeveloperAPI } from "./DeveloperAPI";
|
||||
export { NotifyAPI } from "./NotifyAPI";
|
||||
export { PermissionAPI } from "./PermissionAPI";
|
||||
export { RoleAPI } from "./RoleAPI";
|
||||
export { SettingAPI } from "./SettingAPI";
|
||||
export { UserAPI } from "./UserAPI";
|
||||
@@ -0,0 +1,150 @@
|
||||
/**
|
||||
* 文章编辑器的公共数据处理。
|
||||
* 负责统一内容类型、附件标识和存储前的富文本格式,平台层不参与这些规则。
|
||||
*/
|
||||
import type { ArticleContentType, Attachment } from "../types";
|
||||
import { ATTACHMENT_ID_ATTR, isLocalMediaId, normalizeContent, TEMP_FILE_ID_ATTR } from "timi-web/editor";
|
||||
|
||||
/** 文章内容中附件和临时文件的标识前缀。 */
|
||||
export const ATTACHMENT_ID_PREFIX = "attachment-id:";
|
||||
export const TEMP_FILE_ID_PREFIX = "temp-file-id:";
|
||||
export const ARTICLE_IMAGE_ATTACH_TYPE = "CONTENT_IMAGE";
|
||||
export const ARTICLE_VIDEO_ATTACH_TYPE = "CONTENT_VIDEO";
|
||||
/** 支持的文章内容类型和默认类型。 */
|
||||
export const DEFAULT_ARTICLE_CONTENT_TYPE: ArticleContentType = "TIP_TAP";
|
||||
export const ARTICLE_CONTENT_TYPE_LIST: ArticleContentType[] = ["TEXT", "MARKDOWN", "TIP_TAP"];
|
||||
|
||||
/** 将后端历史值和未知值归一化为当前支持的内容类型。 */
|
||||
export function normalizeArticleContentType(contentType?: string): ArticleContentType {
|
||||
return ARTICLE_CONTENT_TYPE_LIST.includes(contentType as ArticleContentType) ? contentType as ArticleContentType : DEFAULT_ARTICLE_CONTENT_TYPE;
|
||||
}
|
||||
|
||||
/** 将空内容转换为空字符串,避免编辑器收到 undefined。 */
|
||||
export function normalizeRawArticleContent(content?: string) {
|
||||
return content || "";
|
||||
}
|
||||
|
||||
/** 从媒体 src 中读取持久化附件 ID。 */
|
||||
export function getAttachmentIdFromSrc(src?: string) {
|
||||
if (!src?.startsWith(ATTACHMENT_ID_PREFIX)) {
|
||||
return "";
|
||||
}
|
||||
return src.slice(ATTACHMENT_ID_PREFIX.length);
|
||||
}
|
||||
|
||||
/** 从媒体 src 中读取临时文件 ID。 */
|
||||
export function getTempFileIdFromSrc(src?: string) {
|
||||
if (!src?.startsWith(TEMP_FILE_ID_PREFIX)) {
|
||||
return "";
|
||||
}
|
||||
return src.slice(TEMP_FILE_ID_PREFIX.length);
|
||||
}
|
||||
|
||||
/** 构造带有附件 ID 的内部媒体地址。 */
|
||||
export function buildAttachmentIdSrc(attachmentId: string) {
|
||||
return `${ATTACHMENT_ID_PREFIX}${attachmentId}`;
|
||||
}
|
||||
|
||||
/** 根据媒体标签判断附件类型。 */
|
||||
function getMediaAttachType(tagName: string) {
|
||||
return tagName.toLowerCase() === "video" ? ARTICLE_VIDEO_ATTACH_TYPE : ARTICLE_IMAGE_ATTACH_TYPE;
|
||||
}
|
||||
|
||||
/** 仅为 blob 预览地址保留预览元数据,服务器地址不重复保存。 */
|
||||
function buildAttachmentMetadata(src: string) {
|
||||
if (!src.startsWith("blob:")) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
previewUrl: src
|
||||
};
|
||||
}
|
||||
|
||||
/** 过滤本地临时媒体 ID,避免把前端占位 ID 当成可上传附件。 */
|
||||
function normalizeAttachmentTempFileId(tempFileId?: string) {
|
||||
if (!tempFileId || isLocalMediaId(tempFileId)) {
|
||||
return undefined;
|
||||
}
|
||||
return tempFileId;
|
||||
}
|
||||
|
||||
/** 从文章 HTML 中提取图片和视频附件,并按 ID 去重。 */
|
||||
export function buildAttachmentListFromContent(content?: string) {
|
||||
const rawContent = normalizeContent(content);
|
||||
if (!rawContent) {
|
||||
return [] as Attachment[];
|
||||
}
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(rawContent, "text/html");
|
||||
const mediaList = Array.from(doc.querySelectorAll("img, video"));
|
||||
const attachmentMap = new Map<string, Attachment>();
|
||||
|
||||
for (const media of mediaList) {
|
||||
const src = media.getAttribute("src") || "";
|
||||
const attachmentId = media.getAttribute(ATTACHMENT_ID_ATTR) || getAttachmentIdFromSrc(src);
|
||||
const tempFileId = media.getAttribute(TEMP_FILE_ID_ATTR) || getTempFileIdFromSrc(src);
|
||||
const key = attachmentId || tempFileId;
|
||||
if (!key || attachmentMap.has(key)) {
|
||||
continue;
|
||||
}
|
||||
attachmentMap.set(key, {
|
||||
id: attachmentId || key,
|
||||
tempFileId: normalizeAttachmentTempFileId(tempFileId),
|
||||
name: media.getAttribute("title") || media.getAttribute("alt") || "",
|
||||
attachType: getMediaAttachType(media.tagName),
|
||||
metadata: buildAttachmentMetadata(src)
|
||||
});
|
||||
}
|
||||
|
||||
return Array.from(attachmentMap.values());
|
||||
}
|
||||
|
||||
/** 将媒体地址统一改写为附件地址,供后端保存文章内容。 */
|
||||
export function normalizeContentForStore(content?: string) {
|
||||
const rawContent = normalizeContent(content);
|
||||
if (!rawContent) {
|
||||
return "";
|
||||
}
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(rawContent, "text/html");
|
||||
const mediaList = Array.from(doc.querySelectorAll("img, video"));
|
||||
for (const media of mediaList) {
|
||||
const src = media.getAttribute("src") || "";
|
||||
const attachmentId = media.getAttribute(ATTACHMENT_ID_ATTR) || getAttachmentIdFromSrc(src);
|
||||
const tempFileId = media.getAttribute(TEMP_FILE_ID_ATTR) || getTempFileIdFromSrc(src);
|
||||
const finalAttachmentId = attachmentId || tempFileId;
|
||||
if (!finalAttachmentId) {
|
||||
continue;
|
||||
}
|
||||
media.setAttribute(ATTACHMENT_ID_ATTR, finalAttachmentId);
|
||||
media.removeAttribute(TEMP_FILE_ID_ATTR);
|
||||
media.setAttribute("src", buildAttachmentIdSrc(finalAttachmentId));
|
||||
}
|
||||
return normalizeContent(doc.body.innerHTML);
|
||||
}
|
||||
|
||||
/** 比较附件列表的业务字段,不比较对象引用。 */
|
||||
export function sameAttachmentList(left?: Attachment[], right?: Attachment[]) {
|
||||
const leftList = left || [];
|
||||
const rightList = right || [];
|
||||
if (leftList.length !== rightList.length) {
|
||||
return false;
|
||||
}
|
||||
for (let i = 0; i < leftList.length; i += 1) {
|
||||
const leftItem = leftList[i];
|
||||
const rightItem = rightList[i];
|
||||
if (!rightItem) {
|
||||
return false;
|
||||
}
|
||||
if (leftItem.id !== rightItem.id) {
|
||||
return false;
|
||||
}
|
||||
if ((leftItem.tempFileId || "") !== (rightItem.tempFileId || "")) {
|
||||
return false;
|
||||
}
|
||||
if ((leftItem.accessKey?.value || "") !== (rightItem.accessKey?.value || "")) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/** 业务编辑器数据适配和通用编辑器能力出口。 */
|
||||
export * from "timi-web/editor";
|
||||
export * from "./article";
|
||||
export * from "./notify";
|
||||
export type { Article, ArticleContentType } from "../types/Article";
|
||||
export type { Attachment } from "../types/Attachment";
|
||||
export type { NotifyDetail } from "../types/Notify";
|
||||
@@ -0,0 +1,10 @@
|
||||
/** 通知编辑器的公共数据规则。 */
|
||||
import type { NotifyContentType } from "../types";
|
||||
|
||||
/** 通知缺少内容类型时默认使用 Tiptap。 */
|
||||
export const DEFAULT_NOTIFY_CONTENT_TYPE: NotifyContentType = "TIP_TAP";
|
||||
|
||||
/** 规范化通知内容类型,兼容旧通知未返回内容类型的情况。 */
|
||||
export function normalizeNotifyContentType(contentType?: string): NotifyContentType {
|
||||
return contentType === "TEXT" ? "TEXT" : DEFAULT_NOTIFY_CONTENT_TYPE;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export * from "./api";
|
||||
export { axios } from "./api/BaseAPI";
|
||||
export * from "./editor";
|
||||
export * from "./store";
|
||||
export * from "./types";
|
||||
export * from "./utils";
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./userStore";
|
||||
@@ -0,0 +1,217 @@
|
||||
import {defineStore} from "pinia";
|
||||
import {computed, reactive, readonly, ref} from "vue";
|
||||
import type {CaptchaData, LoginRequest, LoginResponse, LoginUser} from "../types";
|
||||
import {Cooker, Storage} from "timi-web";
|
||||
import {UserAPI} from "../api";
|
||||
|
||||
/** 用户 Store 配置项 */
|
||||
interface UserStoreOptions {
|
||||
/** localStorage 储存 key,默认 "loginUser" */
|
||||
storageKey?: string;
|
||||
}
|
||||
|
||||
/** 访问控制匹配模式 */
|
||||
export type AccessMatchMode = "and" | "or";
|
||||
|
||||
let _storageKey = "loginUser";
|
||||
|
||||
type AccessItem = string | {
|
||||
moduleCode?: string;
|
||||
code?: string;
|
||||
};
|
||||
|
||||
function normalizeAccessItem(item?: AccessItem): string {
|
||||
if (!item) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (typeof item === "string") {
|
||||
return item.trim();
|
||||
}
|
||||
|
||||
const code = item.code?.trim();
|
||||
if (!code) {
|
||||
return "";
|
||||
}
|
||||
|
||||
const moduleCode = item.moduleCode?.trim();
|
||||
return moduleCode && !code.includes(":") ? `${moduleCode}:${code}` : code;
|
||||
}
|
||||
|
||||
function normalizeAccessList(list?: AccessItem[]): string[] {
|
||||
if (!list?.length) {
|
||||
return [];
|
||||
}
|
||||
return list
|
||||
.map(normalizeAccessItem)
|
||||
.filter((item): item is string => !!item);
|
||||
}
|
||||
|
||||
function matchAccess(sourceList?: string[], targetList?: string | string[], mode: AccessMatchMode = "or"): boolean {
|
||||
const normalizedTargetList = normalizeAccessList(Array.isArray(targetList) ? targetList : [targetList || ""]);
|
||||
if (!normalizedTargetList.length) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const sourceSet = new Set(normalizeAccessList(sourceList));
|
||||
if (!sourceSet.size) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (mode === "and") {
|
||||
return normalizedTargetList.every(item => sourceSet.has(item));
|
||||
}
|
||||
return normalizedTargetList.some(item => sourceSet.has(item));
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置用户 Store,应在使用 useUserStore 之前调用
|
||||
* @param options 配置项
|
||||
*/
|
||||
function configureUserStore(options: UserStoreOptions): void {
|
||||
if (options.storageKey) {
|
||||
_storageKey = options.storageKey;
|
||||
}
|
||||
}
|
||||
|
||||
const useUserStore = defineStore("user", () => {
|
||||
type LoginUserState = LoginUser & Record<string, unknown>;
|
||||
|
||||
const loginUser = reactive<LoginUserState>({});
|
||||
const isRestored = ref(false);
|
||||
|
||||
const token = computed(() => loginUser.token ?? "");
|
||||
const isLoggedIn = computed(() => isValidLoginUser(loginUser));
|
||||
|
||||
function resetLoginUser(nextUser?: LoginUserState): void {
|
||||
Object.keys(loginUser).forEach((key) => {
|
||||
delete loginUser[key];
|
||||
});
|
||||
if (nextUser) {
|
||||
Object.assign(loginUser, nextUser);
|
||||
}
|
||||
}
|
||||
|
||||
function isValidLoginUser(user?: LoginUserState | null): user is LoginResponse {
|
||||
return !!user?.token && !!user.expireAt && new Date().getTime() < user.expireAt;
|
||||
}
|
||||
|
||||
function isLogged(): boolean {
|
||||
return isLoggedIn.value;
|
||||
}
|
||||
|
||||
function getLoginUser<T extends LoginUser = LoginUser>(): T | null {
|
||||
if (!isLogged()) {
|
||||
return null;
|
||||
}
|
||||
return loginUser as T;
|
||||
}
|
||||
|
||||
function getRoleList(): string[] {
|
||||
return normalizeAccessList(loginUser.user?.roleList);
|
||||
}
|
||||
|
||||
function getPermissionList(): string[] {
|
||||
return normalizeAccessList(loginUser.user?.permissionList);
|
||||
}
|
||||
|
||||
function hasRoles(roleList: string | string[], mode: AccessMatchMode = "or"): boolean {
|
||||
return matchAccess(getRoleList(), roleList, mode);
|
||||
}
|
||||
|
||||
function hasPermissions(permissionList: string | string[], mode: AccessMatchMode = "or"): boolean {
|
||||
return matchAccess(getPermissionList(), permissionList, mode);
|
||||
}
|
||||
|
||||
async function login<T extends LoginUser = LoginUser>(req: CaptchaData<LoginRequest>): Promise<T> {
|
||||
const result = await UserAPI.login(req);
|
||||
const nextUser = result as unknown as T;
|
||||
await updateLoginUser(nextUser);
|
||||
return nextUser;
|
||||
}
|
||||
|
||||
async function loginByToken<T extends LoginUser = LoginUser>(token: string): Promise<T | null> {
|
||||
loginUser.token = token;
|
||||
// 未过期
|
||||
try {
|
||||
const result = await UserAPI.loginByToken();
|
||||
if (!result) {
|
||||
return null;
|
||||
}
|
||||
const nextUser = result as unknown as T;
|
||||
await updateLoginUser(nextUser);
|
||||
return nextUser;
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
clearLoginUser();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function loginByStorage<T extends LoginUser = LoginUser>(): Promise<T | null> {
|
||||
if (loginUser.token) {
|
||||
isRestored.value = true;
|
||||
return getLoginUser<T>();
|
||||
}
|
||||
|
||||
if (!Storage.has(_storageKey)) {
|
||||
isRestored.value = true;
|
||||
return null;
|
||||
}
|
||||
|
||||
// 未登录,储存有令牌。
|
||||
const storageUser = Storage.getJSON(_storageKey) as T;
|
||||
if (isValidLoginUser(storageUser)) {
|
||||
const result = await loginByToken<T>(storageUser.token);
|
||||
isRestored.value = true;
|
||||
return result;
|
||||
}
|
||||
|
||||
clearLoginUser();
|
||||
isRestored.value = true;
|
||||
return null;
|
||||
}
|
||||
|
||||
async function updateLoginUser<T extends LoginUser = LoginUser>(user: T): Promise<void> {
|
||||
resetLoginUser(user as LoginUserState);
|
||||
Storage.setJSON(_storageKey, user);
|
||||
}
|
||||
|
||||
function clearLoginUser(): void {
|
||||
resetLoginUser();
|
||||
Cooker.remove("Token");
|
||||
Storage.remove(_storageKey);
|
||||
}
|
||||
|
||||
async function logout(): Promise<void> {
|
||||
try {
|
||||
await UserAPI.logout();
|
||||
} finally {
|
||||
clearLoginUser();
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
token,
|
||||
isLoggedIn,
|
||||
isRestored,
|
||||
getRoleList,
|
||||
getPermissionList,
|
||||
hasRoles,
|
||||
hasPermissions,
|
||||
isLogged,
|
||||
loginUser: readonly(loginUser),
|
||||
getLoginUser,
|
||||
login,
|
||||
loginByToken,
|
||||
loginByStorage,
|
||||
updateLoginUser,
|
||||
clearLoginUser,
|
||||
logout
|
||||
};
|
||||
});
|
||||
|
||||
export {
|
||||
useUserStore,
|
||||
configureUserStore
|
||||
};
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { Attachment } from "./Attachment";
|
||||
import type { Comment } from "./Comment";
|
||||
import type { Model } from "./Model";
|
||||
import type { Setting } from "./Setting";
|
||||
|
||||
/** 文章业务类型 */
|
||||
export type ArticleBizType = "BLOG" | "FEEDBACK";
|
||||
|
||||
/** 文章正文类型 */
|
||||
export type ArticleContentType = "TEXT" | "MARKDOWN" | "TIP_TAP";
|
||||
|
||||
/** 文章状态 */
|
||||
export type ArticleStatus = "DART" | "NORMAL" | "HIDDEN";
|
||||
|
||||
/** 文章实体 */
|
||||
export type Article = {
|
||||
/** 业务类型 */
|
||||
bizType?: ArticleBizType;
|
||||
|
||||
/** 业务 ID */
|
||||
bizId?: string;
|
||||
|
||||
/** 标题 */
|
||||
title?: string;
|
||||
|
||||
/** 描述 */
|
||||
description?: string;
|
||||
|
||||
/** 正文类型 */
|
||||
contentType?: ArticleContentType;
|
||||
|
||||
/** 正文内容 */
|
||||
content?: string;
|
||||
|
||||
/** 阅读数量 */
|
||||
reads?: number;
|
||||
|
||||
/** 喜欢数量 */
|
||||
likes?: number;
|
||||
|
||||
/** 文章状态 */
|
||||
status?: ArticleStatus;
|
||||
|
||||
/** 设置列表 */
|
||||
settingList?: Setting[];
|
||||
|
||||
/** 评论列表 */
|
||||
commentList?: Comment[];
|
||||
|
||||
/** 附件列表 */
|
||||
attachmentList?: Attachment[];
|
||||
} & Model;
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { Model } from "./Model";
|
||||
|
||||
export type Attachment = {
|
||||
bizType?: AttachmentBizType;
|
||||
bizId?: string;
|
||||
attachType?: string;
|
||||
mongoId?: string;
|
||||
title?: string;
|
||||
name?: string;
|
||||
mimeType?: string;
|
||||
metadata?: Record<string, any>;
|
||||
accessKey?: AttachmentAccessKey;
|
||||
size?: number;
|
||||
md5?: string;
|
||||
uploaderIp?: string;
|
||||
isDestroyed?: boolean;
|
||||
destroyAt?: number;
|
||||
tempFileId?: string;
|
||||
} & Model;
|
||||
|
||||
export type TempFile = {
|
||||
id: string;
|
||||
expireAt?: number;
|
||||
};
|
||||
|
||||
export type BizIdUpdate = {
|
||||
bizType: AttachmentBizType;
|
||||
bizId: string;
|
||||
items: Partial<Attachment>[];
|
||||
};
|
||||
|
||||
export type AttachmentBizType =
|
||||
| "ARTICLE"
|
||||
| "USER"
|
||||
| "GAO_CUSTOMER"
|
||||
| "GAO_EVENT_RECORD"
|
||||
| "GAO_REGISTER_RECORD"
|
||||
| "TEMP_FILE"
|
||||
| "MIRROR";
|
||||
|
||||
/** 附件访问密钥 */
|
||||
export type AttachmentAccessKey = {
|
||||
value: string;
|
||||
attachmentId: string;
|
||||
isDisposable: boolean;
|
||||
expiredAt: number;
|
||||
createdAt: number;
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { Model, Page } from "./Model";
|
||||
import type { User } from "./User";
|
||||
|
||||
/** 评论 */
|
||||
export type Comment = {
|
||||
bizType?: CommentBizType;
|
||||
bizId?: number;
|
||||
userId?: number;
|
||||
nick?: string;
|
||||
content?: string;
|
||||
|
||||
/** 所属用户 */
|
||||
user?: User;
|
||||
|
||||
/** 回复列表 */
|
||||
replies?: Comment[];
|
||||
|
||||
/** 回复分页 */
|
||||
repliesPage?: Page<Comment>;
|
||||
|
||||
/** 用于绑定组件当前页下标 */
|
||||
repliesCurrent?: number;
|
||||
|
||||
/** 回复数量 */
|
||||
repliesLength?: number;
|
||||
|
||||
/** 关联文章 */
|
||||
article?: object;
|
||||
|
||||
/** 关联 Git 仓库 */
|
||||
repository?: object;
|
||||
} & Model
|
||||
|
||||
export type CommentBizType = "ARTICLE" | "GIT_ISSUE" | "GIT_MERGE";
|
||||
@@ -0,0 +1,6 @@
|
||||
/** 开发者配置 */
|
||||
export type Developer = {
|
||||
developerId?: number;
|
||||
name?: string;
|
||||
rsa?: string;
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// 基本实体模型
|
||||
export type Model = {
|
||||
id?: string;
|
||||
|
||||
createdAt?: number;
|
||||
updatedAt?: number;
|
||||
deletedAt?: number;
|
||||
}
|
||||
|
||||
export type ApiResponse<T = unknown> = {
|
||||
code: number;
|
||||
message: string;
|
||||
messageCode: string;
|
||||
success: boolean;
|
||||
fail: boolean;
|
||||
data: T;
|
||||
}
|
||||
|
||||
export type Page<T> = {
|
||||
orderMap?: { [K in keyof T]?: OrderType };
|
||||
equalsExample?: Partial<T>;
|
||||
likesExample?: Partial<T>;
|
||||
} & BasePage;
|
||||
|
||||
export type BasePage = {
|
||||
index: number;
|
||||
size: number;
|
||||
}
|
||||
|
||||
export type OrderType = "ASC" | "DESC";
|
||||
|
||||
export type PageResult<T> = {
|
||||
total: number;
|
||||
list: T[];
|
||||
}
|
||||
|
||||
// 携带验证码的请求体
|
||||
export type CaptchaData<T> = {
|
||||
captchaId: string;
|
||||
captcha: string;
|
||||
data: T;
|
||||
}
|
||||
|
||||
// 图形验证码
|
||||
export type CaptchaResult = {
|
||||
id: string;
|
||||
data: string;
|
||||
}
|
||||
|
||||
/** 用户背景图和头像的图片渲染样式。 */
|
||||
export const ImageType = {
|
||||
"IR-AUTO": "ir-auto",
|
||||
"IR-SMOOTH": "ir-smooth",
|
||||
"IR-PIXELATED": "ir-pixelated"
|
||||
} as const;
|
||||
|
||||
export type ImageType = keyof typeof ImageType;
|
||||
|
||||
export type KeyValue<V, K = string> = {
|
||||
key: K;
|
||||
value?: V;
|
||||
}
|
||||
|
||||
export type LabelValue<L, V = string> = {
|
||||
label: L;
|
||||
value?: V;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import type { Model } from "./Model";
|
||||
import type { Attachment } from "./Attachment";
|
||||
import type { User } from "./User";
|
||||
|
||||
/** 通知消息类型 */
|
||||
export type NotifyMsgType = "INTERNAL" | "SMS" | "MAIL" | "HTTP" | "WECHAT";
|
||||
|
||||
/** 通知投递状态 */
|
||||
export type NotifyStatus = "WAITING" | "REMINDED" | "TIMEOUT" | "CANCEL" | "FAIL";
|
||||
|
||||
/** 通知内容类型 */
|
||||
export type NotifyContentType = "TEXT" | "TIP_TAP";
|
||||
|
||||
/** 通知 */
|
||||
export type Notify = {
|
||||
/** 业务类型 */
|
||||
bizType?: string;
|
||||
/** 提醒业务类型 */
|
||||
bizRemindedType?: string;
|
||||
/** 提醒业务 ID */
|
||||
bizRemindedId?: string;
|
||||
/** 参数 */
|
||||
args?: string;
|
||||
/** 创建者 */
|
||||
createdBy?: string;
|
||||
/** 通知详情列表 */
|
||||
detailList?: NotifyDetail[];
|
||||
} & Model;
|
||||
|
||||
/** 管理端通知列表项 */
|
||||
export type NotifyManagementItem = {
|
||||
/** 创建者用户 ID */
|
||||
createdBy?: string;
|
||||
/** 通知标题 */
|
||||
subject?: string;
|
||||
/** 通知内容 */
|
||||
content?: string;
|
||||
/** 内容类型 */
|
||||
contentType?: NotifyContentType;
|
||||
/** 发送时间 */
|
||||
sendAt?: number;
|
||||
/** 接收用户数量 */
|
||||
recipientCount?: number;
|
||||
/** 已读用户数量 */
|
||||
readCount?: number;
|
||||
/** 等待发送数量 */
|
||||
waitingCount?: number;
|
||||
/** 已发送数量 */
|
||||
remindedCount?: number;
|
||||
/** 超时数量 */
|
||||
timeoutCount?: number;
|
||||
/** 已取消数量 */
|
||||
cancelCount?: number;
|
||||
/** 失败数量 */
|
||||
failCount?: number;
|
||||
} & Model;
|
||||
|
||||
/** 通知详情 */
|
||||
export type NotifyDetail = {
|
||||
/** 所属通知 ID */
|
||||
notifyId?: string;
|
||||
/** 消息类型 */
|
||||
msgType?: NotifyMsgType;
|
||||
/** 模板 ID */
|
||||
templateId?: string;
|
||||
/** 标题 */
|
||||
subject?: string;
|
||||
/** 内容 */
|
||||
content?: string;
|
||||
/** 内容类型 */
|
||||
contentType?: NotifyContentType;
|
||||
/** 媒体附件列表 */
|
||||
attachmentList?: Attachment[];
|
||||
/** 参数 */
|
||||
args?: string;
|
||||
/** 发送来源 */
|
||||
sendFrom?: string;
|
||||
/** 发送去向 */
|
||||
sendTo?: string;
|
||||
/** 发送时间 */
|
||||
sendAt?: number;
|
||||
/** 重试计数 */
|
||||
retry?: number;
|
||||
/** 超时时间 */
|
||||
timeoutAt?: number;
|
||||
/** 结果描述 */
|
||||
resultDesc?: string;
|
||||
/** 投递状态 */
|
||||
status?: NotifyStatus;
|
||||
/** 已读时间,站内通知未读时为空 */
|
||||
readAt?: number;
|
||||
/** 所属通知 */
|
||||
notify?: Notify;
|
||||
/** 发送用户 */
|
||||
fromUser?: User;
|
||||
/** 接收用户 */
|
||||
toUser?: User;
|
||||
} & Model;
|
||||
@@ -0,0 +1,24 @@
|
||||
export type ModuleCode = "CORE" | "GAO";
|
||||
|
||||
export interface Permission {
|
||||
id: string;
|
||||
moduleCode: ModuleCode;
|
||||
code: string;
|
||||
nameLangId?: string;
|
||||
name?: string;
|
||||
description?: string;
|
||||
builtin?: boolean;
|
||||
protectedPermission?: boolean;
|
||||
ownerType?: AuthOwnerType;
|
||||
ownerId?: string;
|
||||
createdBy?: string;
|
||||
createdAt?: number;
|
||||
updatedAt?: number;
|
||||
deletedAt?: number;
|
||||
}
|
||||
|
||||
export type AuthOwnerType = "SYSTEM" | "MODULE" | "TENANT" | "STORE" | "USER";
|
||||
|
||||
export type PermissionPayload = Pick<Permission, "moduleCode" | "code" | "nameLangId" | "name" | "description"> & {
|
||||
id?: string;
|
||||
};
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { AuthOwnerType, ModuleCode, Permission } from "./Permission";
|
||||
import type { Model } from "./Model";
|
||||
|
||||
export type Role = {
|
||||
moduleCode: ModuleCode;
|
||||
code: string;
|
||||
nameLangId?: string;
|
||||
name?: string;
|
||||
description?: string;
|
||||
builtin?: boolean;
|
||||
protectedRole?: boolean;
|
||||
parentRoleId?: string;
|
||||
ownerType?: AuthOwnerType;
|
||||
ownerId?: string;
|
||||
createdBy?: string;
|
||||
|
||||
permissionList?: Permission[];
|
||||
allPermissionList?: Permission[];
|
||||
childRoleList?: Role[];
|
||||
parentRole?: Role;
|
||||
delegationPermissionList?: Permission[];
|
||||
permissionIdList?: string[];
|
||||
childRoleIdList?: string[];
|
||||
delegationPermissionIdList?: string[];
|
||||
} & Model;
|
||||
|
||||
export type RolePayload = Partial<Pick<Role, "moduleCode" | "code" | "nameLangId" | "name" | "description">> & {
|
||||
id?: string;
|
||||
parentRoleId?: string;
|
||||
ownerType?: AuthOwnerType;
|
||||
ownerId?: string;
|
||||
permissionIdList?: string[];
|
||||
childRoleIdList?: string[];
|
||||
delegationPermissionIdList?: string[];
|
||||
};
|
||||
|
||||
export interface AuthorizeUserRole {
|
||||
userId: string;
|
||||
moduleCode?: ModuleCode;
|
||||
roleIdList?: string[];
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import type {Model} from "./Model";
|
||||
|
||||
export type SettingValueType =
|
||||
| "STRING"
|
||||
| "SELECT_RADIO"
|
||||
| "SELECT_CHECKBOX"
|
||||
| "INTEGER"
|
||||
| "COLOR"
|
||||
| "FLOAT"
|
||||
| "DATE"
|
||||
| "DATETIME"
|
||||
| "TIME"
|
||||
| "DURATION"
|
||||
| "BOOLEAN"
|
||||
| "JSON_LIST"
|
||||
| "JSON_OBJECT"
|
||||
;
|
||||
|
||||
export type Setting = {
|
||||
module: string;
|
||||
key: string;
|
||||
title?: string;
|
||||
description?: string;
|
||||
value?: string;
|
||||
valueType: SettingValueType;
|
||||
valueArgs?: any;
|
||||
} & Model;
|
||||
@@ -0,0 +1,98 @@
|
||||
import { ImageType } from "./Model";
|
||||
import type { Model } from "./Model";
|
||||
import type { Attachment } from "./Attachment";
|
||||
import type { Setting } from "./Setting";
|
||||
import type { Role } from "./Role";
|
||||
|
||||
export type Gender = "MALE" | "FEMALE";
|
||||
|
||||
export type User = {
|
||||
name: string;
|
||||
nick?: string;
|
||||
password?: string;
|
||||
email?: string;
|
||||
emailVerifyAt?: number;
|
||||
phoneNo?: string;
|
||||
phoneNoVerifyAt?: number;
|
||||
wrapperType?: ImageType;
|
||||
avatarType?: ImageType;
|
||||
exp?: number;
|
||||
gender?: Gender;
|
||||
birthdate?: number;
|
||||
qq?: string;
|
||||
description?: string;
|
||||
lastLoginIP?: string;
|
||||
lastLoginAt?: number;
|
||||
unmuteAt?: number;
|
||||
unbanAt?: number;
|
||||
|
||||
roleList?: string[];
|
||||
roleEntityList?: Role[];
|
||||
permissionList?: string[];
|
||||
attachmentList?: Attachment[];
|
||||
settingList?: Setting[];
|
||||
tempFileIdList?: string[];
|
||||
muting?: boolean;
|
||||
banning?: boolean;
|
||||
emailVerified?: boolean;
|
||||
phoneNoVerified?: boolean;
|
||||
} & Model;
|
||||
|
||||
/** 用户资料组件使用的用户视图。 */
|
||||
export type UserView = {
|
||||
id?: string;
|
||||
name: string;
|
||||
profile: {
|
||||
wrapperType?: ImageType;
|
||||
avatarType?: ImageType;
|
||||
exp?: number;
|
||||
sex?: number;
|
||||
description?: string;
|
||||
attachmentList?: Attachment[];
|
||||
};
|
||||
};
|
||||
|
||||
export type UserAttachType = "AVATAR" | "WRAPPER";
|
||||
|
||||
export type RegisterRequest = {
|
||||
name: string;
|
||||
password: string;
|
||||
email?: string;
|
||||
};
|
||||
|
||||
export type LoginRequest = {
|
||||
user: string;
|
||||
password: string;
|
||||
};
|
||||
|
||||
export type SmsLoginRequest = {
|
||||
detailId: string;
|
||||
captcha: string;
|
||||
};
|
||||
|
||||
export type UpdatePasswordRequest = {
|
||||
oldValue: string;
|
||||
newValue: string;
|
||||
};
|
||||
|
||||
// 登录返回
|
||||
export type LoginResponse = {
|
||||
id: string;
|
||||
token: string;
|
||||
expireAt: number;
|
||||
user?: User;
|
||||
};
|
||||
|
||||
export type LoginUser = {
|
||||
id?: string;
|
||||
token?: string;
|
||||
expireAt?: number;
|
||||
user?: User;
|
||||
};
|
||||
|
||||
export type UserLevelType = {
|
||||
exp: number; // 经验数值,和 UserData.exp 一样
|
||||
value: number; // 经验对应等级,[0, 8]
|
||||
percent: number; // 该经验在该等级的百分比 [0, 1]
|
||||
nextLevelUp: number; // 下一级经验值
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export * from "./Article";
|
||||
export * from "./Attachment";
|
||||
export * from "./Comment";
|
||||
export * from "./Developer";
|
||||
export * from "./Model";
|
||||
export * from "./Notify";
|
||||
export * from "./Permission";
|
||||
export * from "./Role";
|
||||
export * from "./Setting";
|
||||
export * from "./User";
|
||||
@@ -0,0 +1,118 @@
|
||||
import axios, { type AxiosInstance, type AxiosResponse, type InternalAxiosRequestConfig } from "axios";
|
||||
import type { ApiResponse } from "../types";
|
||||
|
||||
/** 当前后端服务的响应包装。 */
|
||||
export type ErrorCallback = (response: ApiResponse) => void;
|
||||
export type RequestInterceptor = (config: InternalAxiosRequestConfig) => InternalAxiosRequestConfig;
|
||||
export interface ResponseObserverPayload {
|
||||
config?: InternalAxiosRequestConfig;
|
||||
status?: number;
|
||||
response?: AxiosResponse;
|
||||
error?: unknown;
|
||||
serverResponse?: ApiResponse;
|
||||
}
|
||||
export type ResponseObserver = (payload: ResponseObserverPayload) => void;
|
||||
|
||||
let globalErrorCallback: ErrorCallback | null = null;
|
||||
let globalRequestInterceptor: RequestInterceptor | null = null;
|
||||
let globalResponseObserver: ResponseObserver | null = null;
|
||||
|
||||
export const setGlobalErrorCallback = (callback: ErrorCallback) => {
|
||||
globalErrorCallback = callback;
|
||||
};
|
||||
|
||||
export const setGlobalRequestInterceptor = (callback: RequestInterceptor | null) => {
|
||||
globalRequestInterceptor = callback;
|
||||
};
|
||||
|
||||
export const setGlobalResponseObserver = (callback: ResponseObserver | null) => {
|
||||
globalResponseObserver = callback;
|
||||
};
|
||||
|
||||
const notifyResponseObserver = (payload: ResponseObserverPayload) => {
|
||||
if (!globalResponseObserver) {
|
||||
return;
|
||||
}
|
||||
globalResponseObserver(payload);
|
||||
};
|
||||
|
||||
const applyDefaultInterceptors = (instance: AxiosInstance) => {
|
||||
instance.defaults.withCredentials = true;
|
||||
instance.interceptors.request.use((config) => {
|
||||
if (globalRequestInterceptor) {
|
||||
return globalRequestInterceptor(config);
|
||||
}
|
||||
return config;
|
||||
});
|
||||
instance.interceptors.response.use((axiosResp: AxiosResponse) => {
|
||||
if (!axiosResp.config.responseType) {
|
||||
const serverResp = axiosResp.data as ApiResponse;
|
||||
if (serverResp.code < 40000) {
|
||||
notifyResponseObserver({
|
||||
config: axiosResp.config,
|
||||
status: axiosResp.status,
|
||||
response: axiosResp,
|
||||
serverResponse: serverResp
|
||||
});
|
||||
return serverResp.data;
|
||||
}
|
||||
notifyResponseObserver({
|
||||
config: axiosResp.config,
|
||||
status: axiosResp.status,
|
||||
response: axiosResp,
|
||||
serverResponse: serverResp,
|
||||
error: serverResp.message
|
||||
});
|
||||
if (globalErrorCallback) {
|
||||
globalErrorCallback(serverResp);
|
||||
}
|
||||
return Promise.reject(serverResp.message);
|
||||
}
|
||||
notifyResponseObserver({
|
||||
config: axiosResp.config,
|
||||
status: axiosResp.status,
|
||||
response: axiosResp
|
||||
});
|
||||
return axiosResp.data;
|
||||
}, (error: unknown) => {
|
||||
const axiosError = error as {
|
||||
config?: InternalAxiosRequestConfig;
|
||||
response?: AxiosResponse;
|
||||
request?: unknown;
|
||||
message?: string;
|
||||
};
|
||||
notifyResponseObserver({
|
||||
config: axiosError.config,
|
||||
status: axiosError.response?.status,
|
||||
response: axiosError.response,
|
||||
error
|
||||
});
|
||||
if (axiosError.response?.status) {
|
||||
throw error;
|
||||
}
|
||||
if (axiosError.request) {
|
||||
if (axiosError.message?.startsWith("timeout")) {
|
||||
throw new Error("time out");
|
||||
}
|
||||
throw new Error(axiosError.message || "request error");
|
||||
}
|
||||
throw error;
|
||||
});
|
||||
};
|
||||
|
||||
const axiosInstance = axios.create();
|
||||
applyDefaultInterceptors(axiosInstance);
|
||||
|
||||
export const createServiceAxios = (baseURL?: string) => {
|
||||
const instance = axios.create({ baseURL });
|
||||
applyDefaultInterceptors(instance);
|
||||
return instance;
|
||||
};
|
||||
|
||||
export default {
|
||||
axios: axiosInstance,
|
||||
setGlobalErrorCallback,
|
||||
setGlobalRequestInterceptor,
|
||||
setGlobalResponseObserver,
|
||||
createServiceAxios
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { UserLevelType } from "../types/User";
|
||||
|
||||
/** 根据经验值计算用户等级。 */
|
||||
export function toUserLevel(exp = 0): UserLevelType {
|
||||
const levels = [0, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096];
|
||||
for (let i = 1; i < levels.length; i++) {
|
||||
if (exp < levels[i]) {
|
||||
return {
|
||||
exp,
|
||||
value: i - 1,
|
||||
percent: (exp - levels[i - 1]) / (levels[i] - levels[i - 1]),
|
||||
nextLevelUp: i === levels.length - 1 ? 4096 : levels[i]
|
||||
};
|
||||
}
|
||||
}
|
||||
return {
|
||||
exp,
|
||||
value: 8,
|
||||
percent: 1,
|
||||
nextLevelUp: 4096
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
import type { Directive, DirectiveBinding, EffectScope } from "vue";
|
||||
import { effectScope, watch } from "vue";
|
||||
import { useUserStore } from "../../store";
|
||||
import type { AccessMatchMode } from "../../store";
|
||||
|
||||
/** 访问控制类型 */
|
||||
export type AccessControlType = "permission" | "role";
|
||||
/** 指令结果生效方式 */
|
||||
export type AccessEffectMode = "if" | "show";
|
||||
|
||||
/** 自定义回调参数 */
|
||||
export type AccessDirectiveCallbackPayload = {
|
||||
type: AccessControlType;
|
||||
granted: boolean;
|
||||
valueList: string[];
|
||||
mode: AccessMatchMode;
|
||||
el: HTMLElement;
|
||||
}
|
||||
|
||||
/**
|
||||
* 访问控制指令配置
|
||||
* `value` 支持单个值或值数组
|
||||
* 数组默认按 `or` 逻辑处理,需要 `and` 时显式传 `mode`
|
||||
* `callback` 存在时优先执行回调,不再使用 `effect`
|
||||
*/
|
||||
export type AccessDirectiveConfig = {
|
||||
value: string | string[];
|
||||
mode?: AccessMatchMode;
|
||||
effect?: AccessEffectMode;
|
||||
reverse?: boolean;
|
||||
display?: string;
|
||||
callback?: (payload: AccessDirectiveCallbackPayload) => void;
|
||||
}
|
||||
|
||||
type AccessDirectiveValue = string | string[] | AccessDirectiveConfig;
|
||||
|
||||
type AccessDirectiveState = {
|
||||
scope: EffectScope;
|
||||
placeholder: Comment | null;
|
||||
display: string;
|
||||
config: AccessDirectiveConfig;
|
||||
lastGranted?: boolean;
|
||||
}
|
||||
|
||||
type AccessMatcher = (store: ReturnType<typeof useUserStore>, valueList: string[], mode: AccessMatchMode) => boolean;
|
||||
|
||||
const ACCESS_STATE_KEY = "__vAccessState";
|
||||
|
||||
/** 过滤空字符串并统一裁剪空白 */
|
||||
function normalizeValueList(value: string | string[]): string[] {
|
||||
return (Array.isArray(value) ? value : [value])
|
||||
.map(item => item?.trim())
|
||||
.filter((item): item is string => !!item);
|
||||
}
|
||||
|
||||
/** 统一把指令值转成标准配置 */
|
||||
function normalizeConfig(value: AccessDirectiveValue): AccessDirectiveConfig {
|
||||
if (typeof value === "string" || Array.isArray(value)) {
|
||||
return {
|
||||
value,
|
||||
mode: "or",
|
||||
effect: "if",
|
||||
reverse: false
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
value: value?.value || [],
|
||||
mode: value?.mode || "or",
|
||||
effect: value?.effect || "if",
|
||||
reverse: !!value?.reverse,
|
||||
display: value?.display,
|
||||
callback: value?.callback
|
||||
};
|
||||
}
|
||||
|
||||
/** 恢复被 `if` 模式替换掉的真实元素 */
|
||||
function restoreElement(el: HTMLElement, state: AccessDirectiveState): void {
|
||||
if (state.placeholder?.parentNode) {
|
||||
state.placeholder.parentNode.replaceChild(el, state.placeholder);
|
||||
}
|
||||
state.placeholder = null;
|
||||
}
|
||||
|
||||
/** `if` 模式:无权限时直接移出 DOM */
|
||||
function applyIfEffect(el: HTMLElement, state: AccessDirectiveState, granted: boolean): void {
|
||||
if (granted) {
|
||||
restoreElement(el, state);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!state.placeholder && el.parentNode) {
|
||||
state.placeholder = document.createComment("v-access");
|
||||
el.parentNode.replaceChild(state.placeholder, el);
|
||||
}
|
||||
}
|
||||
|
||||
/** `show` 模式:保留 DOM,仅切换 display */
|
||||
function applyShowEffect(el: HTMLElement, state: AccessDirectiveState, granted: boolean): void {
|
||||
restoreElement(el, state);
|
||||
el.style.display = granted ? state.display : "none";
|
||||
}
|
||||
|
||||
/** 自定义模式:交给调用方自己处理样式或行为 */
|
||||
function applyCustomCallback(
|
||||
el: HTMLElement,
|
||||
state: AccessDirectiveState,
|
||||
granted: boolean,
|
||||
type: AccessControlType,
|
||||
valueList: string[],
|
||||
mode: AccessMatchMode
|
||||
): void {
|
||||
restoreElement(el, state);
|
||||
if (state.lastGranted === granted) {
|
||||
return;
|
||||
}
|
||||
|
||||
state.config.callback?.({
|
||||
type,
|
||||
granted,
|
||||
valueList,
|
||||
mode,
|
||||
el
|
||||
});
|
||||
}
|
||||
|
||||
/** 根据当前登录用户状态刷新指令效果 */
|
||||
function updateAccess(
|
||||
el: HTMLElement,
|
||||
state: AccessDirectiveState,
|
||||
type: AccessControlType,
|
||||
matcher: AccessMatcher
|
||||
): void {
|
||||
const store = useUserStore();
|
||||
const config = state.config;
|
||||
const mode = config.mode || "or";
|
||||
const valueList = normalizeValueList(config.value);
|
||||
const granted = config.reverse ? !matcher(store, valueList, mode) : matcher(store, valueList, mode);
|
||||
|
||||
if (config.callback) {
|
||||
applyCustomCallback(el, state, granted, type, valueList, mode);
|
||||
} else if (config.effect === "show") {
|
||||
applyShowEffect(el, state, granted);
|
||||
} else {
|
||||
applyIfEffect(el, state, granted);
|
||||
}
|
||||
|
||||
state.lastGranted = granted;
|
||||
}
|
||||
|
||||
function getState(el: HTMLElement): AccessDirectiveState | undefined {
|
||||
return (el as HTMLElement & { [ACCESS_STATE_KEY]?: AccessDirectiveState })[ACCESS_STATE_KEY];
|
||||
}
|
||||
|
||||
function setState(el: HTMLElement, state: AccessDirectiveState): void {
|
||||
(el as HTMLElement & { [ACCESS_STATE_KEY]?: AccessDirectiveState })[ACCESS_STATE_KEY] = state;
|
||||
}
|
||||
|
||||
function clearState(el: HTMLElement): void {
|
||||
delete (el as HTMLElement & { [ACCESS_STATE_KEY]?: AccessDirectiveState })[ACCESS_STATE_KEY];
|
||||
}
|
||||
|
||||
/** 卸载时清掉占位注释,避免遗留无用节点 */
|
||||
function clearPlaceholder(state: AccessDirectiveState): void {
|
||||
if (state.placeholder?.parentNode) {
|
||||
state.placeholder.parentNode.removeChild(state.placeholder);
|
||||
}
|
||||
state.placeholder = null;
|
||||
}
|
||||
|
||||
/** 创建角色/权限通用指令 */
|
||||
function createAccessDirective(type: AccessControlType, matcher: AccessMatcher): Directive<HTMLElement, AccessDirectiveValue> {
|
||||
return {
|
||||
mounted(el: HTMLElement, binding: DirectiveBinding<AccessDirectiveValue>) {
|
||||
const state: AccessDirectiveState = {
|
||||
scope: effectScope(),
|
||||
placeholder: null,
|
||||
display: el.style.display,
|
||||
config: normalizeConfig(binding.value)
|
||||
};
|
||||
|
||||
setState(el, state);
|
||||
|
||||
state.scope.run(() => {
|
||||
const store = useUserStore();
|
||||
watch(
|
||||
() => {
|
||||
return type === "permission" ? store.getPermissionList().join("|") : store.getRoleList().join("|");
|
||||
},
|
||||
() => updateAccess(el, state, type, matcher),
|
||||
{ immediate: true }
|
||||
);
|
||||
});
|
||||
},
|
||||
updated(el: HTMLElement, binding: DirectiveBinding<AccessDirectiveValue>) {
|
||||
const state = getState(el);
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
|
||||
state.config = normalizeConfig(binding.value);
|
||||
updateAccess(el, state, type, matcher);
|
||||
},
|
||||
unmounted(el: HTMLElement) {
|
||||
const state = getState(el);
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
|
||||
state.scope.stop();
|
||||
clearPlaceholder(state);
|
||||
clearState(el);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** 权限指令:`v-can` */
|
||||
export const VCan = createAccessDirective("permission", (store, valueList, mode) => {
|
||||
return store.hasPermissions(valueList, mode);
|
||||
});
|
||||
|
||||
/** 角色指令:`v-role` */
|
||||
export const VRole = createAccessDirective("role", (store, valueList, mode) => {
|
||||
return store.hasRoles(valueList, mode);
|
||||
});
|
||||
|
||||
export default VCan;
|
||||
@@ -0,0 +1,5 @@
|
||||
export { default as VCan } from "./directives/Access";
|
||||
export * from "./directives/Access";
|
||||
export { default as Network } from "./Network";
|
||||
export * from "./Network";
|
||||
export { toUserLevel } from "./User";
|
||||
Reference in New Issue
Block a user