import { createApiClient } from "../lib/apiClient"; import type { RoleDto } from "../types/role"; const api = createApiClient({ getToken: () => { try { return localStorage.getItem("access_token") ?? localStorage.getItem("token") ?? null; } catch { return null; } }, }); const PATH = "/rbac-role"; export type RbacRoleUpsertInput = { roleName: string; roleCode: string; remark?: string | null; dataScope?: number | null; state: boolean; orderNum?: number | null; }; export async function createRbacRole(input: RbacRoleUpsertInput): Promise { return api.requestJson({ path: PATH, method: "POST", body: input, }); } export async function updateRbacRole(id: string, input: RbacRoleUpsertInput): Promise { return api.requestJson({ path: `${PATH}/${encodeURIComponent(id)}`, method: "PUT", body: input, }); } function extractMenuIdsFromRoleDetail(raw: unknown): string[] { if (!raw || typeof raw !== "object") return []; const r = raw as Record; // 常见命名:menuIds / MenuIds const direct = Array.isArray(r.menuIds) ? r.menuIds : Array.isArray((r as any).MenuIds) ? (r as any).MenuIds : undefined; if (direct) return (direct as unknown[]).map(String); // 包一层:{ data: { menuIds } } const data = (r as any).data ?? (r as any).Data; if (data && typeof data === "object") { const dd = data as Record; const fromData = Array.isArray(dd.menuIds) ? dd.menuIds : Array.isArray(dd.MenuIds) ? dd.MenuIds : undefined; if (fromData) return (fromData as unknown[]).map(String); } // 可能是 roleMenus: [{ menuId: '...' }] 之类 const roleMenus = Array.isArray((r as any).roleMenus) ? (r as any).roleMenus : Array.isArray((r as any).RoleMenus) ? (r as any).RoleMenus : undefined; if (Array.isArray(roleMenus)) { const ids: string[] = []; for (const x of roleMenus) { if (!x || typeof x !== "object") continue; const rr = x as Record; const mid = rr.menuId ?? rr.MenuId ?? rr.id ?? rr.Id; if (mid) ids.push(String(mid)); } return ids; } return []; } /** * Swagger(常见约定):DELETE /api/app/rbac-role,Body 为 ID 数组 */ export async function deleteRbacRoles(ids: string[]): Promise { if (!ids.length) return; await api.requestJson({ path: PATH, method: "DELETE", body: ids, }); } export async function deleteRbacRole(id: string): Promise { await deleteRbacRoles([id]); } /** * Swagger: GET /api/app/rbac-role/{id} * 用于“查看当前角色菜单权限”,尽量从返回对象里提取 menuIds 字段。 */ export async function getRbacRoleMenuIds(roleId: string, signal?: AbortSignal): Promise { const raw = await api.requestJson({ path: `${PATH}/${encodeURIComponent(roleId)}`, method: "GET", signal, }); return extractMenuIdsFromRoleDetail(raw); }