roleService.ts
2.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import { ApiError, createApiClient } from "../lib/apiClient";
import type { PagedResultDto, RoleDto, RoleGetListInput } from "../types/role";
const api = createApiClient({
getToken: () => {
try {
return localStorage.getItem("access_token") ?? localStorage.getItem("token") ?? null;
} catch {
return null;
}
},
});
// ABP Conventional Controller for RoleService
const PATH = "/role";
export async function getRoles(input: RoleGetListInput, signal?: AbortSignal): Promise<PagedResultDto<RoleDto>> {
return api.requestJson<PagedResultDto<RoleDto>>({
path: PATH,
method: "GET",
query: {
SkipCount: input.skipCount,
MaxResultCount: input.maxResultCount,
RoleName: input.roleName,
RoleCode: input.roleCode,
State: input.state,
},
signal,
});
}
function getBaseUrl(): string {
return import.meta.env.VITE_API_BASE_URL ?? "http://localhost:19001";
}
function getToken(): string | null {
try {
return localStorage.getItem("access_token") ?? localStorage.getItem("token") ?? null;
} catch {
return null;
}
}
function joinUrl(baseUrl: string, path: string): string {
const b = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
const p = path.startsWith("/") ? path : `/${path}`;
return `${b}${p}`;
}
function toQueryString(params: Record<string, unknown>): string {
const qs = new URLSearchParams();
for (const [k, v] of Object.entries(params)) {
if (v === undefined || v === null || v === "") continue;
if (typeof v === "boolean") {
qs.set(k, v ? "true" : "false");
continue;
}
qs.set(k, String(v));
}
const s = qs.toString();
return s ? `?${s}` : "";
}
export type RoleExportQuery = {
roleName?: string;
roleCode?: string;
state?: boolean;
};
/** POST /api/app/role/export-pdf — ABP `Export*` 为 POST */
export async function exportRolesPdf(input: RoleExportQuery, signal?: AbortSignal): Promise<Blob> {
const baseUrl = getBaseUrl();
const token = getToken();
const url = joinUrl(
baseUrl,
`/api/app/role/export-pdf${toQueryString({
RoleName: input.roleName,
RoleCode: input.roleCode,
State: input.state,
})}`,
);
const headers: Record<string, string> = {};
if (token) headers.Authorization = `Bearer ${token}`;
const res = await fetch(url, { method: "POST", headers, signal });
if (!res.ok) {
const ct = res.headers.get("content-type") ?? "";
let msg = "Export failed.";
if (ct.includes("application/json")) {
const payload = await res.json().catch(() => null);
const m =
(payload as { error?: { message?: string } })?.error?.message?.trim() ||
(payload as { message?: string })?.message?.trim();
if (m) msg = m;
} else {
const t = await res.text().catch(() => "");
if (t.trim()) msg = t.trim();
}
throw new ApiError(msg, res.status, null);
}
return res.blob();
}